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"
37 #include "lang_features.h"
38 #include "walk_statements.h"
40 #include "adt/bitfiddle.h"
41 #include "adt/error.h"
42 #include "adt/array.h"
44 //#define PRINT_TOKENS
45 #define MAX_LOOKAHEAD 1
50 entity_namespace_t namespc;
53 typedef struct argument_list_t argument_list_t;
54 struct argument_list_t {
56 argument_list_t *next;
59 typedef struct gnu_attribute_t gnu_attribute_t;
60 struct gnu_attribute_t {
61 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
62 gnu_attribute_t *next;
63 bool invalid; /**< Set if this attribute had argument errors, */
64 bool has_arguments; /**< True, if this attribute has arguments. */
69 long argument; /**< Single argument. */
70 argument_list_t *arguments; /**< List of argument expressions. */
74 typedef struct declaration_specifiers_t declaration_specifiers_t;
75 struct declaration_specifiers_t {
76 source_position_t source_position;
77 storage_class_t storage_class;
78 unsigned char alignment; /**< Alignment, 0 if not set. */
80 bool thread_local : 1; /**< GCC __thread */
82 decl_modifiers_t modifiers; /**< declaration modifiers */
83 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
84 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
85 symbol_t *get_property_sym; /**< the name of the get property if set. */
86 symbol_t *put_property_sym; /**< the name of the put property if set. */
91 * An environment for parsing initializers (and compound literals).
93 typedef struct parse_initializer_env_t {
94 type_t *type; /**< the type of the initializer. In case of an
95 array type with unspecified size this gets
96 adjusted to the actual size. */
97 entity_t *entity; /**< the variable that is initialized if any */
98 bool must_be_constant;
99 } parse_initializer_env_t;
102 * Capture a MS __base extension.
104 typedef struct based_spec_t {
105 source_position_t source_position;
106 variable_t *base_variable;
109 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
111 /** The current token. */
112 static token_t token;
113 /** The lookahead ring-buffer. */
114 static token_t lookahead_buffer[MAX_LOOKAHEAD];
115 /** Position of the next token in the lookahead buffer. */
116 static size_t lookahead_bufpos;
117 static stack_entry_t *environment_stack = NULL;
118 static stack_entry_t *label_stack = NULL;
119 static scope_t *file_scope = NULL;
120 static scope_t *current_scope = NULL;
121 /** Point to the current function declaration if inside a function. */
122 static function_t *current_function = NULL;
123 static entity_t *current_init_decl = NULL;
124 static switch_statement_t *current_switch = NULL;
125 static statement_t *current_loop = NULL;
126 static statement_t *current_parent = NULL;
127 static ms_try_statement_t *current_try = NULL;
128 static linkage_kind_t current_linkage = LINKAGE_INVALID;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t **goto_anchor = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t **label_anchor = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
140 static entity_t *anonymous_entity;
141 static declaration_t **incomplete_arrays;
144 #define PUSH_PARENT(stmt) \
145 statement_t *const prev_parent = current_parent; \
146 ((void)(current_parent = (stmt)))
147 #define POP_PARENT ((void)(current_parent = prev_parent))
149 /** special symbol used for anonymous entities. */
150 static const symbol_t *sym_anonymous = NULL;
152 /* symbols for Microsoft extended-decl-modifier */
153 static const symbol_t *sym_align = NULL;
154 static const symbol_t *sym_allocate = NULL;
155 static const symbol_t *sym_dllimport = NULL;
156 static const symbol_t *sym_dllexport = NULL;
157 static const symbol_t *sym_naked = NULL;
158 static const symbol_t *sym_noinline = NULL;
159 static const symbol_t *sym_returns_twice = NULL;
160 static const symbol_t *sym_noreturn = NULL;
161 static const symbol_t *sym_nothrow = NULL;
162 static const symbol_t *sym_novtable = NULL;
163 static const symbol_t *sym_property = NULL;
164 static const symbol_t *sym_get = NULL;
165 static const symbol_t *sym_put = NULL;
166 static const symbol_t *sym_selectany = NULL;
167 static const symbol_t *sym_thread = NULL;
168 static const symbol_t *sym_uuid = NULL;
169 static const symbol_t *sym_deprecated = NULL;
170 static const symbol_t *sym_restrict = NULL;
171 static const symbol_t *sym_noalias = NULL;
173 /** The token anchor set */
174 static unsigned char token_anchor_set[T_LAST_TOKEN];
176 /** The current source position. */
177 #define HERE (&token.source_position)
179 /** true if we are in GCC mode. */
180 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
182 static type_t *type_valist;
184 static statement_t *parse_compound_statement(bool inside_expression_statement);
185 static statement_t *parse_statement(void);
187 static expression_t *parse_sub_expression(precedence_t);
188 static expression_t *parse_expression(void);
189 static type_t *parse_typename(void);
190 static void parse_externals(void);
191 static void parse_external(void);
193 static void parse_compound_type_entries(compound_t *compound_declaration);
195 typedef enum declarator_flags_t {
197 DECL_MAY_BE_ABSTRACT = 1U << 0,
198 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
199 DECL_IS_PARAMETER = 1U << 2
200 } declarator_flags_t;
202 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
203 declarator_flags_t flags);
205 static entity_t *record_entity(entity_t *entity, bool is_definition);
207 static void semantic_comparison(binary_expression_t *expression);
209 #define STORAGE_CLASSES \
210 STORAGE_CLASSES_NO_EXTERN \
213 #define STORAGE_CLASSES_NO_EXTERN \
220 #define TYPE_QUALIFIERS \
225 case T__forceinline: \
226 case T___attribute__:
228 #define COMPLEX_SPECIFIERS \
230 #define IMAGINARY_SPECIFIERS \
233 #define TYPE_SPECIFIERS \
235 case T___builtin_va_list: \
255 #define DECLARATION_START \
260 #define DECLARATION_START_NO_EXTERN \
261 STORAGE_CLASSES_NO_EXTERN \
265 #define TYPENAME_START \
269 #define EXPRESSION_START \
278 case T_CHARACTER_CONSTANT: \
279 case T_FLOATINGPOINT: \
283 case T_STRING_LITERAL: \
284 case T_WIDE_CHARACTER_CONSTANT: \
285 case T_WIDE_STRING_LITERAL: \
286 case T___FUNCDNAME__: \
287 case T___FUNCSIG__: \
288 case T___FUNCTION__: \
289 case T___PRETTY_FUNCTION__: \
290 case T___alignof__: \
291 case T___builtin_alloca: \
292 case T___builtin_classify_type: \
293 case T___builtin_constant_p: \
294 case T___builtin_expect: \
295 case T___builtin_huge_val: \
296 case T___builtin_inf: \
297 case T___builtin_inff: \
298 case T___builtin_infl: \
299 case T___builtin_isgreater: \
300 case T___builtin_isgreaterequal: \
301 case T___builtin_isless: \
302 case T___builtin_islessequal: \
303 case T___builtin_islessgreater: \
304 case T___builtin_isunordered: \
305 case T___builtin_nan: \
306 case T___builtin_nanf: \
307 case T___builtin_nanl: \
308 case T___builtin_offsetof: \
309 case T___builtin_prefetch: \
310 case T___builtin_va_arg: \
311 case T___builtin_va_end: \
312 case T___builtin_va_start: \
313 case T___builtin_return_address: \
314 case T___builtin_frame_address: \
315 case T___builtin_ffs: \
316 case T___builtin_clz: \
317 case T___builtin_ctz: \
318 case T___builtin_popcount: \
319 case T___builtin_parity: \
320 case T___builtin_trap: \
331 * Allocate an AST node with given size and
332 * initialize all fields with zero.
334 static void *allocate_ast_zero(size_t size)
336 void *res = allocate_ast(size);
337 memset(res, 0, size);
342 * Returns the size of an entity node.
344 * @param kind the entity kind
346 static size_t get_entity_struct_size(entity_kind_t kind)
348 static const size_t sizes[] = {
349 [ENTITY_VARIABLE] = sizeof(variable_t),
350 [ENTITY_PARAMETER] = sizeof(parameter_t),
351 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
352 [ENTITY_FUNCTION] = sizeof(function_t),
353 [ENTITY_TYPEDEF] = sizeof(typedef_t),
354 [ENTITY_STRUCT] = sizeof(compound_t),
355 [ENTITY_UNION] = sizeof(compound_t),
356 [ENTITY_ENUM] = sizeof(enum_t),
357 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
358 [ENTITY_LABEL] = sizeof(label_t),
359 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
360 [ENTITY_NAMESPACE] = sizeof(namespace_t)
362 assert(kind < lengthof(sizes));
363 assert(sizes[kind] != 0);
368 * Allocate an entity of given kind and initialize all
371 static entity_t *allocate_entity_zero(entity_kind_t kind)
373 size_t size = get_entity_struct_size(kind);
374 entity_t *entity = allocate_ast_zero(size);
380 * Returns the size of a statement node.
382 * @param kind the statement kind
384 static size_t get_statement_struct_size(statement_kind_t kind)
386 static const size_t sizes[] = {
387 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
388 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
389 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
390 [STATEMENT_RETURN] = sizeof(return_statement_t),
391 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
392 [STATEMENT_IF] = sizeof(if_statement_t),
393 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
394 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
395 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
396 [STATEMENT_BREAK] = sizeof(statement_base_t),
397 [STATEMENT_GOTO] = sizeof(goto_statement_t),
398 [STATEMENT_LABEL] = sizeof(label_statement_t),
399 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
400 [STATEMENT_WHILE] = sizeof(while_statement_t),
401 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
402 [STATEMENT_FOR] = sizeof(for_statement_t),
403 [STATEMENT_ASM] = sizeof(asm_statement_t),
404 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
405 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
407 assert(kind < lengthof(sizes));
408 assert(sizes[kind] != 0);
413 * Returns the size of an expression node.
415 * @param kind the expression kind
417 static size_t get_expression_struct_size(expression_kind_t kind)
419 static const size_t sizes[] = {
420 [EXPR_INVALID] = sizeof(expression_base_t),
421 [EXPR_REFERENCE] = sizeof(reference_expression_t),
422 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
423 [EXPR_CONST] = sizeof(const_expression_t),
424 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
425 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
426 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
427 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
428 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
429 [EXPR_CALL] = sizeof(call_expression_t),
430 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
431 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
432 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
433 [EXPR_SELECT] = sizeof(select_expression_t),
434 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
435 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
436 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
437 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
438 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
439 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
440 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
441 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
442 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
443 [EXPR_VA_START] = sizeof(va_start_expression_t),
444 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
445 [EXPR_STATEMENT] = sizeof(statement_expression_t),
446 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
448 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
449 return sizes[EXPR_UNARY_FIRST];
451 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
452 return sizes[EXPR_BINARY_FIRST];
454 assert(kind < lengthof(sizes));
455 assert(sizes[kind] != 0);
460 * Allocate a statement node of given kind and initialize all
461 * fields with zero. Sets its source position to the position
462 * of the current token.
464 static statement_t *allocate_statement_zero(statement_kind_t kind)
466 size_t size = get_statement_struct_size(kind);
467 statement_t *res = allocate_ast_zero(size);
469 res->base.kind = kind;
470 res->base.parent = current_parent;
471 res->base.source_position = token.source_position;
476 * Allocate an expression node of given kind and initialize all
479 static expression_t *allocate_expression_zero(expression_kind_t kind)
481 size_t size = get_expression_struct_size(kind);
482 expression_t *res = allocate_ast_zero(size);
484 res->base.kind = kind;
485 res->base.type = type_error_type;
486 res->base.source_position = token.source_position;
491 * Creates a new invalid expression at the source position
492 * of the current token.
494 static expression_t *create_invalid_expression(void)
496 return allocate_expression_zero(EXPR_INVALID);
500 * Creates a new invalid statement.
502 static statement_t *create_invalid_statement(void)
504 return allocate_statement_zero(STATEMENT_INVALID);
508 * Allocate a new empty statement.
510 static statement_t *create_empty_statement(void)
512 return allocate_statement_zero(STATEMENT_EMPTY);
516 * Returns the size of a type node.
518 * @param kind the type kind
520 static size_t get_type_struct_size(type_kind_t kind)
522 static const size_t sizes[] = {
523 [TYPE_ATOMIC] = sizeof(atomic_type_t),
524 [TYPE_COMPLEX] = sizeof(complex_type_t),
525 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
526 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
527 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
528 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
529 [TYPE_ENUM] = sizeof(enum_type_t),
530 [TYPE_FUNCTION] = sizeof(function_type_t),
531 [TYPE_POINTER] = sizeof(pointer_type_t),
532 [TYPE_ARRAY] = sizeof(array_type_t),
533 [TYPE_BUILTIN] = sizeof(builtin_type_t),
534 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
535 [TYPE_TYPEOF] = sizeof(typeof_type_t),
537 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
538 assert(kind <= TYPE_TYPEOF);
539 assert(sizes[kind] != 0);
544 * Allocate a type node of given kind and initialize all
547 * @param kind type kind to allocate
549 static type_t *allocate_type_zero(type_kind_t kind)
551 size_t size = get_type_struct_size(kind);
552 type_t *res = obstack_alloc(type_obst, size);
553 memset(res, 0, size);
554 res->base.kind = kind;
560 * Returns the size of an initializer node.
562 * @param kind the initializer kind
564 static size_t get_initializer_size(initializer_kind_t kind)
566 static const size_t sizes[] = {
567 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
568 [INITIALIZER_STRING] = sizeof(initializer_string_t),
569 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
570 [INITIALIZER_LIST] = sizeof(initializer_list_t),
571 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
573 assert(kind < lengthof(sizes));
574 assert(sizes[kind] != 0);
579 * Allocate an initializer node of given kind and initialize all
582 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
584 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
591 * Returns the index of the top element of the environment stack.
593 static size_t environment_top(void)
595 return ARR_LEN(environment_stack);
599 * Returns the index of the top element of the global label stack.
601 static size_t label_top(void)
603 return ARR_LEN(label_stack);
607 * Return the next token.
609 static inline void next_token(void)
611 token = lookahead_buffer[lookahead_bufpos];
612 lookahead_buffer[lookahead_bufpos] = lexer_token;
615 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
618 print_token(stderr, &token);
619 fprintf(stderr, "\n");
624 * Return the next token with a given lookahead.
626 static inline const token_t *look_ahead(size_t num)
628 assert(0 < num && num <= MAX_LOOKAHEAD);
629 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
630 return &lookahead_buffer[pos];
634 * Adds a token type to the token type anchor set (a multi-set).
636 static void add_anchor_token(int token_type)
638 assert(0 <= token_type && token_type < T_LAST_TOKEN);
639 ++token_anchor_set[token_type];
643 * Set the number of tokens types of the given type
644 * to zero and return the old count.
646 static int save_and_reset_anchor_state(int token_type)
648 assert(0 <= token_type && token_type < T_LAST_TOKEN);
649 int count = token_anchor_set[token_type];
650 token_anchor_set[token_type] = 0;
655 * Restore the number of token types to the given count.
657 static void restore_anchor_state(int token_type, int count)
659 assert(0 <= token_type && token_type < T_LAST_TOKEN);
660 token_anchor_set[token_type] = count;
664 * Remove a token type from the token type anchor set (a multi-set).
666 static void rem_anchor_token(int token_type)
668 assert(0 <= token_type && token_type < T_LAST_TOKEN);
669 assert(token_anchor_set[token_type] != 0);
670 --token_anchor_set[token_type];
674 * Return true if the token type of the current token is
677 static bool at_anchor(void)
681 return token_anchor_set[token.type];
685 * Eat tokens until a matching token type is found.
687 static void eat_until_matching_token(int type)
691 case '(': end_token = ')'; break;
692 case '{': end_token = '}'; break;
693 case '[': end_token = ']'; break;
694 default: end_token = type; break;
697 unsigned parenthesis_count = 0;
698 unsigned brace_count = 0;
699 unsigned bracket_count = 0;
700 while (token.type != end_token ||
701 parenthesis_count != 0 ||
703 bracket_count != 0) {
704 switch (token.type) {
706 case '(': ++parenthesis_count; break;
707 case '{': ++brace_count; break;
708 case '[': ++bracket_count; break;
711 if (parenthesis_count > 0)
721 if (bracket_count > 0)
724 if (token.type == end_token &&
725 parenthesis_count == 0 &&
739 * Eat input tokens until an anchor is found.
741 static void eat_until_anchor(void)
743 while (token_anchor_set[token.type] == 0) {
744 if (token.type == '(' || token.type == '{' || token.type == '[')
745 eat_until_matching_token(token.type);
751 * Eat a whole block from input tokens.
753 static void eat_block(void)
755 eat_until_matching_token('{');
756 if (token.type == '}')
760 #define eat(token_type) (assert(token.type == (token_type)), next_token())
763 * Report a parse error because an expected token was not found.
766 #if defined __GNUC__ && __GNUC__ >= 4
767 __attribute__((sentinel))
769 void parse_error_expected(const char *message, ...)
771 if (message != NULL) {
772 errorf(HERE, "%s", message);
775 va_start(ap, message);
776 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
781 * Report an incompatible type.
783 static void type_error_incompatible(const char *msg,
784 const source_position_t *source_position, type_t *type1, type_t *type2)
786 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
791 * Expect the current token is the expected token.
792 * If not, generate an error, eat the current statement,
793 * and goto the end_error label.
795 #define expect(expected, error_label) \
797 if (UNLIKELY(token.type != (expected))) { \
798 parse_error_expected(NULL, (expected), NULL); \
799 add_anchor_token(expected); \
800 eat_until_anchor(); \
801 if (token.type == expected) \
803 rem_anchor_token(expected); \
810 * Push a given scope on the scope stack and make it the
813 static scope_t *scope_push(scope_t *new_scope)
815 if (current_scope != NULL) {
816 new_scope->depth = current_scope->depth + 1;
819 scope_t *old_scope = current_scope;
820 current_scope = new_scope;
825 * Pop the current scope from the scope stack.
827 static void scope_pop(scope_t *old_scope)
829 current_scope = old_scope;
833 * Search an entity by its symbol in a given namespace.
835 static entity_t *get_entity(const symbol_t *const symbol,
836 namespace_tag_t namespc)
838 entity_t *entity = symbol->entity;
839 for (; entity != NULL; entity = entity->base.symbol_next) {
840 if (entity->base.namespc == namespc)
848 * pushs an entity on the environment stack and links the corresponding symbol
851 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
853 symbol_t *symbol = entity->base.symbol;
854 entity_namespace_t namespc = entity->base.namespc;
855 assert(namespc != NAMESPACE_INVALID);
857 /* replace/add entity into entity list of the symbol */
860 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
865 /* replace an entry? */
866 if (iter->base.namespc == namespc) {
867 entity->base.symbol_next = iter->base.symbol_next;
873 /* remember old declaration */
875 entry.symbol = symbol;
876 entry.old_entity = iter;
877 entry.namespc = namespc;
878 ARR_APP1(stack_entry_t, *stack_ptr, entry);
882 * Push an entity on the environment stack.
884 static void environment_push(entity_t *entity)
886 assert(entity->base.source_position.input_name != NULL);
887 assert(entity->base.parent_scope != NULL);
888 stack_push(&environment_stack, entity);
892 * Push a declaration on the global label stack.
894 * @param declaration the declaration
896 static void label_push(entity_t *label)
898 /* we abuse the parameters scope as parent for the labels */
899 label->base.parent_scope = ¤t_function->parameters;
900 stack_push(&label_stack, label);
904 * pops symbols from the environment stack until @p new_top is the top element
906 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
908 stack_entry_t *stack = *stack_ptr;
909 size_t top = ARR_LEN(stack);
912 assert(new_top <= top);
916 for (i = top; i > new_top; --i) {
917 stack_entry_t *entry = &stack[i - 1];
919 entity_t *old_entity = entry->old_entity;
920 symbol_t *symbol = entry->symbol;
921 entity_namespace_t namespc = entry->namespc;
923 /* replace with old_entity/remove */
926 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
928 assert(iter != NULL);
929 /* replace an entry? */
930 if (iter->base.namespc == namespc)
934 /* restore definition from outer scopes (if there was one) */
935 if (old_entity != NULL) {
936 old_entity->base.symbol_next = iter->base.symbol_next;
937 *anchor = old_entity;
939 /* remove entry from list */
940 *anchor = iter->base.symbol_next;
944 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
948 * Pop all entries from the environment stack until the new_top
951 * @param new_top the new stack top
953 static void environment_pop_to(size_t new_top)
955 stack_pop_to(&environment_stack, new_top);
959 * Pop all entries from the global label stack until the new_top
962 * @param new_top the new stack top
964 static void label_pop_to(size_t new_top)
966 stack_pop_to(&label_stack, new_top);
969 static int get_akind_rank(atomic_type_kind_t akind)
975 * Return the type rank for an atomic type.
977 static int get_rank(const type_t *type)
979 assert(!is_typeref(type));
980 if (type->kind == TYPE_ENUM)
981 return get_akind_rank(type->enumt.akind);
983 assert(type->kind == TYPE_ATOMIC);
984 return get_akind_rank(type->atomic.akind);
988 * Do integer promotion for a given type.
990 * @param type the type to promote
991 * @return the promoted type
993 static type_t *promote_integer(type_t *type)
995 if (type->kind == TYPE_BITFIELD)
996 type = type->bitfield.base_type;
998 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
1005 * Create a cast expression.
1007 * @param expression the expression to cast
1008 * @param dest_type the destination type
1010 static expression_t *create_cast_expression(expression_t *expression,
1013 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1015 cast->unary.value = expression;
1016 cast->base.type = dest_type;
1022 * Check if a given expression represents a null pointer constant.
1024 * @param expression the expression to check
1026 static bool is_null_pointer_constant(const expression_t *expression)
1028 /* skip void* cast */
1029 if (expression->kind == EXPR_UNARY_CAST ||
1030 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1031 type_t *const type = skip_typeref(expression->base.type);
1032 if (types_compatible(type, type_void_ptr))
1033 expression = expression->unary.value;
1036 type_t *const type = skip_typeref(expression->base.type);
1038 is_type_integer(type) &&
1039 is_constant_expression(expression) &&
1040 fold_constant(expression) == 0;
1044 * Create an implicit cast expression.
1046 * @param expression the expression to cast
1047 * @param dest_type the destination type
1049 static expression_t *create_implicit_cast(expression_t *expression,
1052 type_t *const source_type = expression->base.type;
1054 if (source_type == dest_type)
1057 return create_cast_expression(expression, dest_type);
1060 typedef enum assign_error_t {
1062 ASSIGN_ERROR_INCOMPATIBLE,
1063 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1064 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1065 ASSIGN_WARNING_POINTER_FROM_INT,
1066 ASSIGN_WARNING_INT_FROM_POINTER
1069 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1070 const expression_t *const right,
1071 const char *context,
1072 const source_position_t *source_position)
1074 type_t *const orig_type_right = right->base.type;
1075 type_t *const type_left = skip_typeref(orig_type_left);
1076 type_t *const type_right = skip_typeref(orig_type_right);
1079 case ASSIGN_SUCCESS:
1081 case ASSIGN_ERROR_INCOMPATIBLE:
1082 errorf(source_position,
1083 "destination type '%T' in %s is incompatible with type '%T'",
1084 orig_type_left, context, orig_type_right);
1087 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1088 if (warning.other) {
1089 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1090 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1092 /* the left type has all qualifiers from the right type */
1093 unsigned missing_qualifiers
1094 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1095 warningf(source_position,
1096 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1097 orig_type_left, context, orig_type_right, missing_qualifiers);
1102 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1103 if (warning.other) {
1104 warningf(source_position,
1105 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1106 orig_type_left, context, right, orig_type_right);
1110 case ASSIGN_WARNING_POINTER_FROM_INT:
1111 if (warning.other) {
1112 warningf(source_position,
1113 "%s makes pointer '%T' from integer '%T' without a cast",
1114 context, orig_type_left, orig_type_right);
1118 case ASSIGN_WARNING_INT_FROM_POINTER:
1119 if (warning.other) {
1120 warningf(source_position,
1121 "%s makes integer '%T' from pointer '%T' without a cast",
1122 context, orig_type_left, orig_type_right);
1127 panic("invalid error value");
1131 /** Implements the rules from §6.5.16.1 */
1132 static assign_error_t semantic_assign(type_t *orig_type_left,
1133 const expression_t *const right)
1135 type_t *const orig_type_right = right->base.type;
1136 type_t *const type_left = skip_typeref(orig_type_left);
1137 type_t *const type_right = skip_typeref(orig_type_right);
1139 if (is_type_pointer(type_left)) {
1140 if (is_null_pointer_constant(right)) {
1141 return ASSIGN_SUCCESS;
1142 } else if (is_type_pointer(type_right)) {
1143 type_t *points_to_left
1144 = skip_typeref(type_left->pointer.points_to);
1145 type_t *points_to_right
1146 = skip_typeref(type_right->pointer.points_to);
1147 assign_error_t res = ASSIGN_SUCCESS;
1149 /* the left type has all qualifiers from the right type */
1150 unsigned missing_qualifiers
1151 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1152 if (missing_qualifiers != 0) {
1153 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1156 points_to_left = get_unqualified_type(points_to_left);
1157 points_to_right = get_unqualified_type(points_to_right);
1159 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1162 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1163 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1164 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1167 if (!types_compatible(points_to_left, points_to_right)) {
1168 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1172 } else if (is_type_integer(type_right)) {
1173 return ASSIGN_WARNING_POINTER_FROM_INT;
1175 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1176 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1177 && is_type_pointer(type_right))) {
1178 return ASSIGN_SUCCESS;
1179 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1180 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1181 type_t *const unqual_type_left = get_unqualified_type(type_left);
1182 type_t *const unqual_type_right = get_unqualified_type(type_right);
1183 if (types_compatible(unqual_type_left, unqual_type_right)) {
1184 return ASSIGN_SUCCESS;
1186 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1187 return ASSIGN_WARNING_INT_FROM_POINTER;
1190 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1191 return ASSIGN_SUCCESS;
1193 return ASSIGN_ERROR_INCOMPATIBLE;
1196 static expression_t *parse_constant_expression(void)
1198 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1200 if (!is_constant_expression(result)) {
1201 errorf(&result->base.source_position,
1202 "expression '%E' is not constant", result);
1208 static expression_t *parse_assignment_expression(void)
1210 return parse_sub_expression(PREC_ASSIGNMENT);
1213 static string_t parse_string_literals(void)
1215 assert(token.type == T_STRING_LITERAL);
1216 string_t result = token.v.string;
1220 while (token.type == T_STRING_LITERAL) {
1221 result = concat_strings(&result, &token.v.string);
1228 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1229 [GNU_AK_CONST] = "const",
1230 [GNU_AK_VOLATILE] = "volatile",
1231 [GNU_AK_CDECL] = "cdecl",
1232 [GNU_AK_STDCALL] = "stdcall",
1233 [GNU_AK_FASTCALL] = "fastcall",
1234 [GNU_AK_DEPRECATED] = "deprecated",
1235 [GNU_AK_NOINLINE] = "noinline",
1236 [GNU_AK_RETURNS_TWICE] = "returns_twice",
1237 [GNU_AK_NORETURN] = "noreturn",
1238 [GNU_AK_NAKED] = "naked",
1239 [GNU_AK_PURE] = "pure",
1240 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1241 [GNU_AK_MALLOC] = "malloc",
1242 [GNU_AK_WEAK] = "weak",
1243 [GNU_AK_CONSTRUCTOR] = "constructor",
1244 [GNU_AK_DESTRUCTOR] = "destructor",
1245 [GNU_AK_NOTHROW] = "nothrow",
1246 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1247 [GNU_AK_COMMON] = "common",
1248 [GNU_AK_NOCOMMON] = "nocommon",
1249 [GNU_AK_PACKED] = "packed",
1250 [GNU_AK_SHARED] = "shared",
1251 [GNU_AK_NOTSHARED] = "notshared",
1252 [GNU_AK_USED] = "used",
1253 [GNU_AK_UNUSED] = "unused",
1254 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1255 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1256 [GNU_AK_LONGCALL] = "longcall",
1257 [GNU_AK_SHORTCALL] = "shortcall",
1258 [GNU_AK_LONG_CALL] = "long_call",
1259 [GNU_AK_SHORT_CALL] = "short_call",
1260 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1261 [GNU_AK_INTERRUPT] = "interrupt",
1262 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1263 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1264 [GNU_AK_NESTING] = "nesting",
1265 [GNU_AK_NEAR] = "near",
1266 [GNU_AK_FAR] = "far",
1267 [GNU_AK_SIGNAL] = "signal",
1268 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1269 [GNU_AK_TINY_DATA] = "tiny_data",
1270 [GNU_AK_SAVEALL] = "saveall",
1271 [GNU_AK_FLATTEN] = "flatten",
1272 [GNU_AK_SSEREGPARM] = "sseregparm",
1273 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1274 [GNU_AK_RETURN_TWICE] = "return_twice",
1275 [GNU_AK_MAY_ALIAS] = "may_alias",
1276 [GNU_AK_MS_STRUCT] = "ms_struct",
1277 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1278 [GNU_AK_DLLIMPORT] = "dllimport",
1279 [GNU_AK_DLLEXPORT] = "dllexport",
1280 [GNU_AK_ALIGNED] = "aligned",
1281 [GNU_AK_ALIAS] = "alias",
1282 [GNU_AK_SECTION] = "section",
1283 [GNU_AK_FORMAT] = "format",
1284 [GNU_AK_FORMAT_ARG] = "format_arg",
1285 [GNU_AK_WEAKREF] = "weakref",
1286 [GNU_AK_NONNULL] = "nonnull",
1287 [GNU_AK_TLS_MODEL] = "tls_model",
1288 [GNU_AK_VISIBILITY] = "visibility",
1289 [GNU_AK_REGPARM] = "regparm",
1290 [GNU_AK_MODE] = "mode",
1291 [GNU_AK_MODEL] = "model",
1292 [GNU_AK_TRAP_EXIT] = "trap_exit",
1293 [GNU_AK_SP_SWITCH] = "sp_switch",
1294 [GNU_AK_SENTINEL] = "sentinel"
1298 * compare two string, ignoring double underscores on the second.
1300 static int strcmp_underscore(const char *s1, const char *s2)
1302 if (s2[0] == '_' && s2[1] == '_') {
1303 size_t len2 = strlen(s2);
1304 size_t len1 = strlen(s1);
1305 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1306 return strncmp(s1, s2+2, len2-4);
1310 return strcmp(s1, s2);
1314 * Allocate a new gnu temporal attribute of given kind.
1316 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1318 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1319 attribute->kind = kind;
1320 attribute->next = NULL;
1321 attribute->invalid = false;
1322 attribute->has_arguments = false;
1328 * Parse one constant expression argument of the given attribute.
1330 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1332 expression_t *expression;
1333 add_anchor_token(')');
1334 expression = parse_constant_expression();
1335 rem_anchor_token(')');
1336 expect(')', end_error);
1337 attribute->u.argument = fold_constant(expression);
1340 attribute->invalid = true;
1344 * Parse a list of constant expressions arguments of the given attribute.
1346 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1348 argument_list_t **list = &attribute->u.arguments;
1349 argument_list_t *entry;
1350 expression_t *expression;
1351 add_anchor_token(')');
1352 add_anchor_token(',');
1354 expression = parse_constant_expression();
1355 entry = obstack_alloc(&temp_obst, sizeof(entry));
1356 entry->argument = fold_constant(expression);
1359 list = &entry->next;
1360 if (token.type != ',')
1364 rem_anchor_token(',');
1365 rem_anchor_token(')');
1366 expect(')', end_error);
1369 attribute->invalid = true;
1373 * Parse one string literal argument of the given attribute.
1375 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1378 add_anchor_token('(');
1379 if (token.type != T_STRING_LITERAL) {
1380 parse_error_expected("while parsing attribute directive",
1381 T_STRING_LITERAL, NULL);
1384 *string = parse_string_literals();
1385 rem_anchor_token('(');
1386 expect(')', end_error);
1389 attribute->invalid = true;
1393 * Parse one tls model of the given attribute.
1395 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1397 static const char *const tls_models[] = {
1403 string_t string = { NULL, 0 };
1404 parse_gnu_attribute_string_arg(attribute, &string);
1405 if (string.begin != NULL) {
1406 for (size_t i = 0; i < 4; ++i) {
1407 if (strcmp(tls_models[i], string.begin) == 0) {
1408 attribute->u.value = i;
1412 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1414 attribute->invalid = true;
1418 * Parse one tls model of the given attribute.
1420 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1422 static const char *const visibilities[] = {
1428 string_t string = { NULL, 0 };
1429 parse_gnu_attribute_string_arg(attribute, &string);
1430 if (string.begin != NULL) {
1431 for (size_t i = 0; i < 4; ++i) {
1432 if (strcmp(visibilities[i], string.begin) == 0) {
1433 attribute->u.value = i;
1437 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1439 attribute->invalid = true;
1443 * Parse one (code) model of the given attribute.
1445 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1447 static const char *const visibilities[] = {
1452 string_t string = { NULL, 0 };
1453 parse_gnu_attribute_string_arg(attribute, &string);
1454 if (string.begin != NULL) {
1455 for (int i = 0; i < 3; ++i) {
1456 if (strcmp(visibilities[i], string.begin) == 0) {
1457 attribute->u.value = i;
1461 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1463 attribute->invalid = true;
1467 * Parse one mode of the given attribute.
1469 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1471 add_anchor_token(')');
1473 if (token.type != T_IDENTIFIER) {
1474 expect(T_IDENTIFIER, end_error);
1477 attribute->u.symbol = token.v.symbol;
1480 rem_anchor_token(')');
1481 expect(')', end_error);
1484 attribute->invalid = true;
1488 * Parse one interrupt argument of the given attribute.
1490 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1492 static const char *const interrupts[] = {
1499 string_t string = { NULL, 0 };
1500 parse_gnu_attribute_string_arg(attribute, &string);
1501 if (string.begin != NULL) {
1502 for (size_t i = 0; i < 5; ++i) {
1503 if (strcmp(interrupts[i], string.begin) == 0) {
1504 attribute->u.value = i;
1508 errorf(HERE, "'%s' is not an interrupt", string.begin);
1510 attribute->invalid = true;
1514 * Parse ( identifier, const expression, const expression )
1516 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1518 static const char *const format_names[] = {
1526 if (token.type != T_IDENTIFIER) {
1527 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1530 const char *name = token.v.symbol->string;
1531 for (i = 0; i < 4; ++i) {
1532 if (strcmp_underscore(format_names[i], name) == 0)
1536 if (warning.attribute)
1537 warningf(HERE, "'%s' is an unrecognized format function type", name);
1541 expect(',', end_error);
1542 add_anchor_token(')');
1543 add_anchor_token(',');
1544 parse_constant_expression();
1545 rem_anchor_token(',');
1546 rem_anchor_token(')');
1548 expect(',', end_error);
1549 add_anchor_token(')');
1550 parse_constant_expression();
1551 rem_anchor_token(')');
1552 expect(')', end_error);
1555 attribute->u.value = true;
1559 * Check that a given GNU attribute has no arguments.
1561 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1563 if (!attribute->has_arguments)
1566 /* should have no arguments */
1567 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1568 eat_until_matching_token('(');
1569 /* we have already consumed '(', so we stop before ')', eat it */
1571 attribute->invalid = true;
1575 * Parse one GNU attribute.
1577 * Note that attribute names can be specified WITH or WITHOUT
1578 * double underscores, ie const or __const__.
1580 * The following attributes are parsed without arguments
1605 * no_instrument_function
1606 * warn_unused_result
1623 * externally_visible
1631 * The following attributes are parsed with arguments
1632 * aligned( const expression )
1633 * alias( string literal )
1634 * section( string literal )
1635 * format( identifier, const expression, const expression )
1636 * format_arg( const expression )
1637 * tls_model( string literal )
1638 * visibility( string literal )
1639 * regparm( const expression )
1640 * model( string leteral )
1641 * trap_exit( const expression )
1642 * sp_switch( string literal )
1644 * The following attributes might have arguments
1645 * weak_ref( string literal )
1646 * non_null( const expression // ',' )
1647 * interrupt( string literal )
1648 * sentinel( constant expression )
1650 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1652 gnu_attribute_t *head = *attributes;
1653 gnu_attribute_t *last = *attributes;
1654 decl_modifiers_t modifiers = 0;
1655 gnu_attribute_t *attribute;
1657 eat(T___attribute__);
1658 expect('(', end_error);
1659 expect('(', end_error);
1661 if (token.type != ')') {
1662 /* find the end of the list */
1664 while (last->next != NULL)
1668 /* non-empty attribute list */
1671 if (token.type == T_const) {
1673 } else if (token.type == T_volatile) {
1675 } else if (token.type == T_cdecl) {
1676 /* __attribute__((cdecl)), WITH ms mode */
1678 } else if (token.type == T_IDENTIFIER) {
1679 const symbol_t *sym = token.v.symbol;
1682 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1689 for (i = 0; i < GNU_AK_LAST; ++i) {
1690 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1693 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1696 if (kind == GNU_AK_LAST) {
1697 if (warning.attribute)
1698 warningf(HERE, "'%s' attribute directive ignored", name);
1700 /* skip possible arguments */
1701 if (token.type == '(') {
1702 eat_until_matching_token(')');
1705 /* check for arguments */
1706 attribute = allocate_gnu_attribute(kind);
1707 if (token.type == '(') {
1709 if (token.type == ')') {
1710 /* empty args are allowed */
1713 attribute->has_arguments = true;
1717 case GNU_AK_VOLATILE:
1722 case GNU_AK_NOCOMMON:
1724 case GNU_AK_NOTSHARED:
1725 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1726 case GNU_AK_WARN_UNUSED_RESULT:
1727 case GNU_AK_LONGCALL:
1728 case GNU_AK_SHORTCALL:
1729 case GNU_AK_LONG_CALL:
1730 case GNU_AK_SHORT_CALL:
1731 case GNU_AK_FUNCTION_VECTOR:
1732 case GNU_AK_INTERRUPT_HANDLER:
1733 case GNU_AK_NMI_HANDLER:
1734 case GNU_AK_NESTING:
1738 case GNU_AK_EIGTHBIT_DATA:
1739 case GNU_AK_TINY_DATA:
1740 case GNU_AK_SAVEALL:
1741 case GNU_AK_FLATTEN:
1742 case GNU_AK_SSEREGPARM:
1743 case GNU_AK_EXTERNALLY_VISIBLE:
1744 case GNU_AK_RETURN_TWICE:
1745 case GNU_AK_MAY_ALIAS:
1746 case GNU_AK_MS_STRUCT:
1747 case GNU_AK_GCC_STRUCT:
1750 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1751 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1752 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1753 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1754 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1755 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1756 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1757 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1758 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1759 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1760 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1761 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1762 case GNU_AK_RETURNS_TWICE: modifiers |= DM_RETURNS_TWICE; goto no_arg;
1763 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1764 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1765 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1766 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1767 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1768 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1770 case GNU_AK_ALIGNED:
1771 /* __align__ may be used without an argument */
1772 if (attribute->has_arguments) {
1773 parse_gnu_attribute_const_arg(attribute);
1777 case GNU_AK_FORMAT_ARG:
1778 case GNU_AK_REGPARM:
1779 case GNU_AK_TRAP_EXIT:
1780 if (!attribute->has_arguments) {
1781 /* should have arguments */
1782 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1783 attribute->invalid = true;
1785 parse_gnu_attribute_const_arg(attribute);
1788 case GNU_AK_SECTION:
1789 case GNU_AK_SP_SWITCH:
1790 if (!attribute->has_arguments) {
1791 /* should have arguments */
1792 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1793 attribute->invalid = true;
1795 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1798 if (!attribute->has_arguments) {
1799 /* should have arguments */
1800 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1801 attribute->invalid = true;
1803 parse_gnu_attribute_format_args(attribute);
1805 case GNU_AK_WEAKREF:
1806 /* may have one string argument */
1807 if (attribute->has_arguments)
1808 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1810 case GNU_AK_NONNULL:
1811 if (attribute->has_arguments)
1812 parse_gnu_attribute_const_arg_list(attribute);
1814 case GNU_AK_TLS_MODEL:
1815 if (!attribute->has_arguments) {
1816 /* should have arguments */
1817 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1819 parse_gnu_attribute_tls_model_arg(attribute);
1821 case GNU_AK_VISIBILITY:
1822 if (!attribute->has_arguments) {
1823 /* should have arguments */
1824 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1826 parse_gnu_attribute_visibility_arg(attribute);
1829 if (!attribute->has_arguments) {
1830 /* should have arguments */
1831 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1833 parse_gnu_attribute_model_arg(attribute);
1837 if (!attribute->has_arguments) {
1838 /* should have arguments */
1839 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1841 parse_gnu_attribute_mode_arg(attribute);
1844 case GNU_AK_INTERRUPT:
1845 /* may have one string argument */
1846 if (attribute->has_arguments)
1847 parse_gnu_attribute_interrupt_arg(attribute);
1849 case GNU_AK_SENTINEL:
1850 /* may have one string argument */
1851 if (attribute->has_arguments)
1852 parse_gnu_attribute_const_arg(attribute);
1855 /* already handled */
1859 check_no_argument(attribute, name);
1862 if (attribute != NULL) {
1864 last->next = attribute;
1867 head = last = attribute;
1871 if (token.type != ',')
1876 expect(')', end_error);
1877 expect(')', end_error);
1885 * Parse GNU attributes.
1887 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1889 decl_modifiers_t modifiers = 0;
1892 switch (token.type) {
1893 case T___attribute__:
1894 modifiers |= parse_gnu_attribute(attributes);
1899 expect('(', end_error);
1900 if (token.type != T_STRING_LITERAL) {
1901 parse_error_expected("while parsing assembler attribute",
1902 T_STRING_LITERAL, NULL);
1903 eat_until_matching_token('(');
1906 parse_string_literals();
1908 expect(')', end_error);
1911 case T_cdecl: modifiers |= DM_CDECL; break;
1912 case T__fastcall: modifiers |= DM_FASTCALL; break;
1913 case T__stdcall: modifiers |= DM_STDCALL; break;
1916 /* TODO record modifier */
1918 warningf(HERE, "Ignoring declaration modifier %K", &token);
1922 default: return modifiers;
1929 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1931 static entity_t *determine_lhs_ent(expression_t *const expr,
1934 switch (expr->kind) {
1935 case EXPR_REFERENCE: {
1936 entity_t *const entity = expr->reference.entity;
1937 /* we should only find variables as lvalues... */
1938 if (entity->base.kind != ENTITY_VARIABLE
1939 && entity->base.kind != ENTITY_PARAMETER)
1945 case EXPR_ARRAY_ACCESS: {
1946 expression_t *const ref = expr->array_access.array_ref;
1947 entity_t * ent = NULL;
1948 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1949 ent = determine_lhs_ent(ref, lhs_ent);
1952 mark_vars_read(expr->select.compound, lhs_ent);
1954 mark_vars_read(expr->array_access.index, lhs_ent);
1959 if (is_type_compound(skip_typeref(expr->base.type))) {
1960 return determine_lhs_ent(expr->select.compound, lhs_ent);
1962 mark_vars_read(expr->select.compound, lhs_ent);
1967 case EXPR_UNARY_DEREFERENCE: {
1968 expression_t *const val = expr->unary.value;
1969 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1971 return determine_lhs_ent(val->unary.value, lhs_ent);
1973 mark_vars_read(val, NULL);
1979 mark_vars_read(expr, NULL);
1984 #define ENT_ANY ((entity_t*)-1)
1987 * Mark declarations, which are read. This is used to detect variables, which
1991 * x is not marked as "read", because it is only read to calculate its own new
1995 * x and y are not detected as "not read", because multiple variables are
1998 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2000 switch (expr->kind) {
2001 case EXPR_REFERENCE: {
2002 entity_t *const entity = expr->reference.entity;
2003 if (entity->kind != ENTITY_VARIABLE
2004 && entity->kind != ENTITY_PARAMETER)
2007 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2008 if (entity->kind == ENTITY_VARIABLE) {
2009 entity->variable.read = true;
2011 entity->parameter.read = true;
2018 // TODO respect pure/const
2019 mark_vars_read(expr->call.function, NULL);
2020 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2021 mark_vars_read(arg->expression, NULL);
2025 case EXPR_CONDITIONAL:
2026 // TODO lhs_decl should depend on whether true/false have an effect
2027 mark_vars_read(expr->conditional.condition, NULL);
2028 if (expr->conditional.true_expression != NULL)
2029 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2030 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2034 if (lhs_ent == ENT_ANY
2035 && !is_type_compound(skip_typeref(expr->base.type)))
2037 mark_vars_read(expr->select.compound, lhs_ent);
2040 case EXPR_ARRAY_ACCESS: {
2041 expression_t *const ref = expr->array_access.array_ref;
2042 mark_vars_read(ref, lhs_ent);
2043 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2044 mark_vars_read(expr->array_access.index, lhs_ent);
2049 mark_vars_read(expr->va_arge.ap, lhs_ent);
2052 case EXPR_UNARY_CAST:
2053 /* Special case: Use void cast to mark a variable as "read" */
2054 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2059 case EXPR_UNARY_THROW:
2060 if (expr->unary.value == NULL)
2063 case EXPR_UNARY_DEREFERENCE:
2064 case EXPR_UNARY_DELETE:
2065 case EXPR_UNARY_DELETE_ARRAY:
2066 if (lhs_ent == ENT_ANY)
2070 case EXPR_UNARY_NEGATE:
2071 case EXPR_UNARY_PLUS:
2072 case EXPR_UNARY_BITWISE_NEGATE:
2073 case EXPR_UNARY_NOT:
2074 case EXPR_UNARY_TAKE_ADDRESS:
2075 case EXPR_UNARY_POSTFIX_INCREMENT:
2076 case EXPR_UNARY_POSTFIX_DECREMENT:
2077 case EXPR_UNARY_PREFIX_INCREMENT:
2078 case EXPR_UNARY_PREFIX_DECREMENT:
2079 case EXPR_UNARY_CAST_IMPLICIT:
2080 case EXPR_UNARY_ASSUME:
2082 mark_vars_read(expr->unary.value, lhs_ent);
2085 case EXPR_BINARY_ADD:
2086 case EXPR_BINARY_SUB:
2087 case EXPR_BINARY_MUL:
2088 case EXPR_BINARY_DIV:
2089 case EXPR_BINARY_MOD:
2090 case EXPR_BINARY_EQUAL:
2091 case EXPR_BINARY_NOTEQUAL:
2092 case EXPR_BINARY_LESS:
2093 case EXPR_BINARY_LESSEQUAL:
2094 case EXPR_BINARY_GREATER:
2095 case EXPR_BINARY_GREATEREQUAL:
2096 case EXPR_BINARY_BITWISE_AND:
2097 case EXPR_BINARY_BITWISE_OR:
2098 case EXPR_BINARY_BITWISE_XOR:
2099 case EXPR_BINARY_LOGICAL_AND:
2100 case EXPR_BINARY_LOGICAL_OR:
2101 case EXPR_BINARY_SHIFTLEFT:
2102 case EXPR_BINARY_SHIFTRIGHT:
2103 case EXPR_BINARY_COMMA:
2104 case EXPR_BINARY_ISGREATER:
2105 case EXPR_BINARY_ISGREATEREQUAL:
2106 case EXPR_BINARY_ISLESS:
2107 case EXPR_BINARY_ISLESSEQUAL:
2108 case EXPR_BINARY_ISLESSGREATER:
2109 case EXPR_BINARY_ISUNORDERED:
2110 mark_vars_read(expr->binary.left, lhs_ent);
2111 mark_vars_read(expr->binary.right, lhs_ent);
2114 case EXPR_BINARY_ASSIGN:
2115 case EXPR_BINARY_MUL_ASSIGN:
2116 case EXPR_BINARY_DIV_ASSIGN:
2117 case EXPR_BINARY_MOD_ASSIGN:
2118 case EXPR_BINARY_ADD_ASSIGN:
2119 case EXPR_BINARY_SUB_ASSIGN:
2120 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2121 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2122 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2123 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2124 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2125 if (lhs_ent == ENT_ANY)
2127 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2128 mark_vars_read(expr->binary.right, lhs_ent);
2133 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2139 case EXPR_CHARACTER_CONSTANT:
2140 case EXPR_WIDE_CHARACTER_CONSTANT:
2141 case EXPR_STRING_LITERAL:
2142 case EXPR_WIDE_STRING_LITERAL:
2143 case EXPR_COMPOUND_LITERAL: // TODO init?
2145 case EXPR_CLASSIFY_TYPE:
2148 case EXPR_BUILTIN_SYMBOL:
2149 case EXPR_BUILTIN_CONSTANT_P:
2150 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
2152 case EXPR_STATEMENT: // TODO
2153 case EXPR_LABEL_ADDRESS:
2154 case EXPR_REFERENCE_ENUM_VALUE:
2158 panic("unhandled expression");
2161 static designator_t *parse_designation(void)
2163 designator_t *result = NULL;
2164 designator_t *last = NULL;
2167 designator_t *designator;
2168 switch (token.type) {
2170 designator = allocate_ast_zero(sizeof(designator[0]));
2171 designator->source_position = token.source_position;
2173 add_anchor_token(']');
2174 designator->array_index = parse_constant_expression();
2175 rem_anchor_token(']');
2176 expect(']', end_error);
2179 designator = allocate_ast_zero(sizeof(designator[0]));
2180 designator->source_position = token.source_position;
2182 if (token.type != T_IDENTIFIER) {
2183 parse_error_expected("while parsing designator",
2184 T_IDENTIFIER, NULL);
2187 designator->symbol = token.v.symbol;
2191 expect('=', end_error);
2195 assert(designator != NULL);
2197 last->next = designator;
2199 result = designator;
2207 static initializer_t *initializer_from_string(array_type_t *type,
2208 const string_t *const string)
2210 /* TODO: check len vs. size of array type */
2213 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2214 initializer->string.string = *string;
2219 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2220 wide_string_t *const string)
2222 /* TODO: check len vs. size of array type */
2225 initializer_t *const initializer =
2226 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2227 initializer->wide_string.string = *string;
2233 * Build an initializer from a given expression.
2235 static initializer_t *initializer_from_expression(type_t *orig_type,
2236 expression_t *expression)
2238 /* TODO check that expression is a constant expression */
2240 /* §6.7.8.14/15 char array may be initialized by string literals */
2241 type_t *type = skip_typeref(orig_type);
2242 type_t *expr_type_orig = expression->base.type;
2243 type_t *expr_type = skip_typeref(expr_type_orig);
2244 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2245 array_type_t *const array_type = &type->array;
2246 type_t *const element_type = skip_typeref(array_type->element_type);
2248 if (element_type->kind == TYPE_ATOMIC) {
2249 atomic_type_kind_t akind = element_type->atomic.akind;
2250 switch (expression->kind) {
2251 case EXPR_STRING_LITERAL:
2252 if (akind == ATOMIC_TYPE_CHAR
2253 || akind == ATOMIC_TYPE_SCHAR
2254 || akind == ATOMIC_TYPE_UCHAR) {
2255 return initializer_from_string(array_type,
2256 &expression->string.value);
2260 case EXPR_WIDE_STRING_LITERAL: {
2261 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2262 if (get_unqualified_type(element_type) == bare_wchar_type) {
2263 return initializer_from_wide_string(array_type,
2264 &expression->wide_string.value);
2275 assign_error_t error = semantic_assign(type, expression);
2276 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2278 report_assign_error(error, type, expression, "initializer",
2279 &expression->base.source_position);
2281 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2283 if (type->kind == TYPE_BITFIELD) {
2284 type = type->bitfield.base_type;
2287 result->value.value = create_implicit_cast(expression, type);
2293 * Checks if a given expression can be used as an constant initializer.
2295 static bool is_initializer_constant(const expression_t *expression)
2297 return is_constant_expression(expression)
2298 || is_address_constant(expression);
2302 * Parses an scalar initializer.
2304 * §6.7.8.11; eat {} without warning
2306 static initializer_t *parse_scalar_initializer(type_t *type,
2307 bool must_be_constant)
2309 /* there might be extra {} hierarchies */
2311 if (token.type == '{') {
2313 warningf(HERE, "extra curly braces around scalar initializer");
2317 } while (token.type == '{');
2320 expression_t *expression = parse_assignment_expression();
2321 mark_vars_read(expression, NULL);
2322 if (must_be_constant && !is_initializer_constant(expression)) {
2323 errorf(&expression->base.source_position,
2324 "Initialisation expression '%E' is not constant",
2328 initializer_t *initializer = initializer_from_expression(type, expression);
2330 if (initializer == NULL) {
2331 errorf(&expression->base.source_position,
2332 "expression '%E' (type '%T') doesn't match expected type '%T'",
2333 expression, expression->base.type, type);
2338 bool additional_warning_displayed = false;
2339 while (braces > 0) {
2340 if (token.type == ',') {
2343 if (token.type != '}') {
2344 if (!additional_warning_displayed && warning.other) {
2345 warningf(HERE, "additional elements in scalar initializer");
2346 additional_warning_displayed = true;
2357 * An entry in the type path.
2359 typedef struct type_path_entry_t type_path_entry_t;
2360 struct type_path_entry_t {
2361 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2363 size_t index; /**< For array types: the current index. */
2364 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2369 * A type path expression a position inside compound or array types.
2371 typedef struct type_path_t type_path_t;
2372 struct type_path_t {
2373 type_path_entry_t *path; /**< An flexible array containing the current path. */
2374 type_t *top_type; /**< type of the element the path points */
2375 size_t max_index; /**< largest index in outermost array */
2379 * Prints a type path for debugging.
2381 static __attribute__((unused)) void debug_print_type_path(
2382 const type_path_t *path)
2384 size_t len = ARR_LEN(path->path);
2386 for (size_t i = 0; i < len; ++i) {
2387 const type_path_entry_t *entry = & path->path[i];
2389 type_t *type = skip_typeref(entry->type);
2390 if (is_type_compound(type)) {
2391 /* in gcc mode structs can have no members */
2392 if (entry->v.compound_entry == NULL) {
2396 fprintf(stderr, ".%s",
2397 entry->v.compound_entry->base.symbol->string);
2398 } else if (is_type_array(type)) {
2399 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2401 fprintf(stderr, "-INVALID-");
2404 if (path->top_type != NULL) {
2405 fprintf(stderr, " (");
2406 print_type(path->top_type);
2407 fprintf(stderr, ")");
2412 * Return the top type path entry, ie. in a path
2413 * (type).a.b returns the b.
2415 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2417 size_t len = ARR_LEN(path->path);
2419 return &path->path[len-1];
2423 * Enlarge the type path by an (empty) element.
2425 static type_path_entry_t *append_to_type_path(type_path_t *path)
2427 size_t len = ARR_LEN(path->path);
2428 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2430 type_path_entry_t *result = & path->path[len];
2431 memset(result, 0, sizeof(result[0]));
2436 * Descending into a sub-type. Enter the scope of the current top_type.
2438 static void descend_into_subtype(type_path_t *path)
2440 type_t *orig_top_type = path->top_type;
2441 type_t *top_type = skip_typeref(orig_top_type);
2443 type_path_entry_t *top = append_to_type_path(path);
2444 top->type = top_type;
2446 if (is_type_compound(top_type)) {
2447 compound_t *compound = top_type->compound.compound;
2448 entity_t *entry = compound->members.entities;
2450 if (entry != NULL) {
2451 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2452 top->v.compound_entry = &entry->declaration;
2453 path->top_type = entry->declaration.type;
2455 path->top_type = NULL;
2457 } else if (is_type_array(top_type)) {
2459 path->top_type = top_type->array.element_type;
2461 assert(!is_type_valid(top_type));
2466 * Pop an entry from the given type path, ie. returning from
2467 * (type).a.b to (type).a
2469 static void ascend_from_subtype(type_path_t *path)
2471 type_path_entry_t *top = get_type_path_top(path);
2473 path->top_type = top->type;
2475 size_t len = ARR_LEN(path->path);
2476 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2480 * Pop entries from the given type path until the given
2481 * path level is reached.
2483 static void ascend_to(type_path_t *path, size_t top_path_level)
2485 size_t len = ARR_LEN(path->path);
2487 while (len > top_path_level) {
2488 ascend_from_subtype(path);
2489 len = ARR_LEN(path->path);
2493 static bool walk_designator(type_path_t *path, const designator_t *designator,
2494 bool used_in_offsetof)
2496 for (; designator != NULL; designator = designator->next) {
2497 type_path_entry_t *top = get_type_path_top(path);
2498 type_t *orig_type = top->type;
2500 type_t *type = skip_typeref(orig_type);
2502 if (designator->symbol != NULL) {
2503 symbol_t *symbol = designator->symbol;
2504 if (!is_type_compound(type)) {
2505 if (is_type_valid(type)) {
2506 errorf(&designator->source_position,
2507 "'.%Y' designator used for non-compound type '%T'",
2511 top->type = type_error_type;
2512 top->v.compound_entry = NULL;
2513 orig_type = type_error_type;
2515 compound_t *compound = type->compound.compound;
2516 entity_t *iter = compound->members.entities;
2517 for (; iter != NULL; iter = iter->base.next) {
2518 if (iter->base.symbol == symbol) {
2523 errorf(&designator->source_position,
2524 "'%T' has no member named '%Y'", orig_type, symbol);
2527 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2528 if (used_in_offsetof) {
2529 type_t *real_type = skip_typeref(iter->declaration.type);
2530 if (real_type->kind == TYPE_BITFIELD) {
2531 errorf(&designator->source_position,
2532 "offsetof designator '%Y' may not specify bitfield",
2538 top->type = orig_type;
2539 top->v.compound_entry = &iter->declaration;
2540 orig_type = iter->declaration.type;
2543 expression_t *array_index = designator->array_index;
2544 assert(designator->array_index != NULL);
2546 if (!is_type_array(type)) {
2547 if (is_type_valid(type)) {
2548 errorf(&designator->source_position,
2549 "[%E] designator used for non-array type '%T'",
2550 array_index, orig_type);
2555 long index = fold_constant(array_index);
2556 if (!used_in_offsetof) {
2558 errorf(&designator->source_position,
2559 "array index [%E] must be positive", array_index);
2560 } else if (type->array.size_constant) {
2561 long array_size = type->array.size;
2562 if (index >= array_size) {
2563 errorf(&designator->source_position,
2564 "designator [%E] (%d) exceeds array size %d",
2565 array_index, index, array_size);
2570 top->type = orig_type;
2571 top->v.index = (size_t) index;
2572 orig_type = type->array.element_type;
2574 path->top_type = orig_type;
2576 if (designator->next != NULL) {
2577 descend_into_subtype(path);
2586 static void advance_current_object(type_path_t *path, size_t top_path_level)
2588 type_path_entry_t *top = get_type_path_top(path);
2590 type_t *type = skip_typeref(top->type);
2591 if (is_type_union(type)) {
2592 /* in unions only the first element is initialized */
2593 top->v.compound_entry = NULL;
2594 } else if (is_type_struct(type)) {
2595 declaration_t *entry = top->v.compound_entry;
2597 entity_t *next_entity = entry->base.next;
2598 if (next_entity != NULL) {
2599 assert(is_declaration(next_entity));
2600 entry = &next_entity->declaration;
2605 top->v.compound_entry = entry;
2606 if (entry != NULL) {
2607 path->top_type = entry->type;
2610 } else if (is_type_array(type)) {
2611 assert(is_type_array(type));
2615 if (!type->array.size_constant || top->v.index < type->array.size) {
2619 assert(!is_type_valid(type));
2623 /* we're past the last member of the current sub-aggregate, try if we
2624 * can ascend in the type hierarchy and continue with another subobject */
2625 size_t len = ARR_LEN(path->path);
2627 if (len > top_path_level) {
2628 ascend_from_subtype(path);
2629 advance_current_object(path, top_path_level);
2631 path->top_type = NULL;
2636 * skip until token is found.
2638 static void skip_until(int type)
2640 while (token.type != type) {
2641 if (token.type == T_EOF)
2648 * skip any {...} blocks until a closing bracket is reached.
2650 static void skip_initializers(void)
2652 if (token.type == '{')
2655 while (token.type != '}') {
2656 if (token.type == T_EOF)
2658 if (token.type == '{') {
2666 static initializer_t *create_empty_initializer(void)
2668 static initializer_t empty_initializer
2669 = { .list = { { INITIALIZER_LIST }, 0 } };
2670 return &empty_initializer;
2674 * Parse a part of an initialiser for a struct or union,
2676 static initializer_t *parse_sub_initializer(type_path_t *path,
2677 type_t *outer_type, size_t top_path_level,
2678 parse_initializer_env_t *env)
2680 if (token.type == '}') {
2681 /* empty initializer */
2682 return create_empty_initializer();
2685 type_t *orig_type = path->top_type;
2686 type_t *type = NULL;
2688 if (orig_type == NULL) {
2689 /* We are initializing an empty compound. */
2691 type = skip_typeref(orig_type);
2694 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2697 designator_t *designator = NULL;
2698 if (token.type == '.' || token.type == '[') {
2699 designator = parse_designation();
2700 goto finish_designator;
2701 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2702 /* GNU-style designator ("identifier: value") */
2703 designator = allocate_ast_zero(sizeof(designator[0]));
2704 designator->source_position = token.source_position;
2705 designator->symbol = token.v.symbol;
2710 /* reset path to toplevel, evaluate designator from there */
2711 ascend_to(path, top_path_level);
2712 if (!walk_designator(path, designator, false)) {
2713 /* can't continue after designation error */
2717 initializer_t *designator_initializer
2718 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2719 designator_initializer->designator.designator = designator;
2720 ARR_APP1(initializer_t*, initializers, designator_initializer);
2722 orig_type = path->top_type;
2723 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2728 if (token.type == '{') {
2729 if (type != NULL && is_type_scalar(type)) {
2730 sub = parse_scalar_initializer(type, env->must_be_constant);
2734 if (env->entity != NULL) {
2736 "extra brace group at end of initializer for '%Y'",
2737 env->entity->base.symbol);
2739 errorf(HERE, "extra brace group at end of initializer");
2742 descend_into_subtype(path);
2744 add_anchor_token('}');
2745 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2747 rem_anchor_token('}');
2750 ascend_from_subtype(path);
2751 expect('}', end_error);
2753 expect('}', end_error);
2754 goto error_parse_next;
2758 /* must be an expression */
2759 expression_t *expression = parse_assignment_expression();
2760 mark_vars_read(expression, NULL);
2762 if (env->must_be_constant && !is_initializer_constant(expression)) {
2763 errorf(&expression->base.source_position,
2764 "Initialisation expression '%E' is not constant",
2769 /* we are already outside, ... */
2770 type_t *const outer_type_skip = skip_typeref(outer_type);
2771 if (is_type_compound(outer_type_skip) &&
2772 !outer_type_skip->compound.compound->complete) {
2773 goto error_parse_next;
2778 /* handle { "string" } special case */
2779 if ((expression->kind == EXPR_STRING_LITERAL
2780 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2781 && outer_type != NULL) {
2782 sub = initializer_from_expression(outer_type, expression);
2784 if (token.type == ',') {
2787 if (token.type != '}' && warning.other) {
2788 warningf(HERE, "excessive elements in initializer for type '%T'",
2791 /* TODO: eat , ... */
2796 /* descend into subtypes until expression matches type */
2798 orig_type = path->top_type;
2799 type = skip_typeref(orig_type);
2801 sub = initializer_from_expression(orig_type, expression);
2805 if (!is_type_valid(type)) {
2808 if (is_type_scalar(type)) {
2809 errorf(&expression->base.source_position,
2810 "expression '%E' doesn't match expected type '%T'",
2811 expression, orig_type);
2815 descend_into_subtype(path);
2819 /* update largest index of top array */
2820 const type_path_entry_t *first = &path->path[0];
2821 type_t *first_type = first->type;
2822 first_type = skip_typeref(first_type);
2823 if (is_type_array(first_type)) {
2824 size_t index = first->v.index;
2825 if (index > path->max_index)
2826 path->max_index = index;
2830 /* append to initializers list */
2831 ARR_APP1(initializer_t*, initializers, sub);
2834 if (warning.other) {
2835 if (env->entity != NULL) {
2836 warningf(HERE, "excess elements in struct initializer for '%Y'",
2837 env->entity->base.symbol);
2839 warningf(HERE, "excess elements in struct initializer");
2845 if (token.type == '}') {
2848 expect(',', end_error);
2849 if (token.type == '}') {
2854 /* advance to the next declaration if we are not at the end */
2855 advance_current_object(path, top_path_level);
2856 orig_type = path->top_type;
2857 if (orig_type != NULL)
2858 type = skip_typeref(orig_type);
2864 size_t len = ARR_LEN(initializers);
2865 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2866 initializer_t *result = allocate_ast_zero(size);
2867 result->kind = INITIALIZER_LIST;
2868 result->list.len = len;
2869 memcpy(&result->list.initializers, initializers,
2870 len * sizeof(initializers[0]));
2872 DEL_ARR_F(initializers);
2873 ascend_to(path, top_path_level+1);
2878 skip_initializers();
2879 DEL_ARR_F(initializers);
2880 ascend_to(path, top_path_level+1);
2885 * Parses an initializer. Parsers either a compound literal
2886 * (env->declaration == NULL) or an initializer of a declaration.
2888 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2890 type_t *type = skip_typeref(env->type);
2891 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2892 initializer_t *result;
2894 if (is_type_scalar(type)) {
2895 result = parse_scalar_initializer(type, env->must_be_constant);
2896 } else if (token.type == '{') {
2900 memset(&path, 0, sizeof(path));
2901 path.top_type = env->type;
2902 path.path = NEW_ARR_F(type_path_entry_t, 0);
2904 descend_into_subtype(&path);
2906 add_anchor_token('}');
2907 result = parse_sub_initializer(&path, env->type, 1, env);
2908 rem_anchor_token('}');
2910 max_index = path.max_index;
2911 DEL_ARR_F(path.path);
2913 expect('}', end_error);
2915 /* parse_scalar_initializer() also works in this case: we simply
2916 * have an expression without {} around it */
2917 result = parse_scalar_initializer(type, env->must_be_constant);
2920 /* §6.7.8:22 array initializers for arrays with unknown size determine
2921 * the array type size */
2922 if (is_type_array(type) && type->array.size_expression == NULL
2923 && result != NULL) {
2925 switch (result->kind) {
2926 case INITIALIZER_LIST:
2927 assert(max_index != 0xdeadbeaf);
2928 size = max_index + 1;
2931 case INITIALIZER_STRING:
2932 size = result->string.string.size;
2935 case INITIALIZER_WIDE_STRING:
2936 size = result->wide_string.string.size;
2939 case INITIALIZER_DESIGNATOR:
2940 case INITIALIZER_VALUE:
2941 /* can happen for parse errors */
2946 internal_errorf(HERE, "invalid initializer type");
2949 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2950 cnst->base.type = type_size_t;
2951 cnst->conste.v.int_value = size;
2953 type_t *new_type = duplicate_type(type);
2955 new_type->array.size_expression = cnst;
2956 new_type->array.size_constant = true;
2957 new_type->array.has_implicit_size = true;
2958 new_type->array.size = size;
2959 env->type = new_type;
2967 static void append_entity(scope_t *scope, entity_t *entity)
2969 if (scope->last_entity != NULL) {
2970 scope->last_entity->base.next = entity;
2972 scope->entities = entity;
2974 scope->last_entity = entity;
2978 static compound_t *parse_compound_type_specifier(bool is_struct)
2980 gnu_attribute_t *attributes = NULL;
2981 decl_modifiers_t modifiers = 0;
2988 symbol_t *symbol = NULL;
2989 compound_t *compound = NULL;
2991 if (token.type == T___attribute__) {
2992 modifiers |= parse_attributes(&attributes);
2995 if (token.type == T_IDENTIFIER) {
2996 symbol = token.v.symbol;
2999 namespace_tag_t const namespc =
3000 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3001 entity_t *entity = get_entity(symbol, namespc);
3002 if (entity != NULL) {
3003 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3004 compound = &entity->compound;
3005 if (compound->base.parent_scope != current_scope &&
3006 (token.type == '{' || token.type == ';')) {
3007 /* we're in an inner scope and have a definition. Shadow
3008 * existing definition in outer scope */
3010 } else if (compound->complete && token.type == '{') {
3011 assert(symbol != NULL);
3012 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3013 is_struct ? "struct" : "union", symbol,
3014 &compound->base.source_position);
3015 /* clear members in the hope to avoid further errors */
3016 compound->members.entities = NULL;
3019 } else if (token.type != '{') {
3021 parse_error_expected("while parsing struct type specifier",
3022 T_IDENTIFIER, '{', NULL);
3024 parse_error_expected("while parsing union type specifier",
3025 T_IDENTIFIER, '{', NULL);
3031 if (compound == NULL) {
3032 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3033 entity_t *entity = allocate_entity_zero(kind);
3034 compound = &entity->compound;
3036 compound->base.namespc =
3037 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3038 compound->base.source_position = token.source_position;
3039 compound->base.symbol = symbol;
3040 compound->base.parent_scope = current_scope;
3041 if (symbol != NULL) {
3042 environment_push(entity);
3044 append_entity(current_scope, entity);
3047 if (token.type == '{') {
3048 parse_compound_type_entries(compound);
3049 modifiers |= parse_attributes(&attributes);
3051 if (symbol == NULL) {
3052 assert(anonymous_entity == NULL);
3053 anonymous_entity = (entity_t*)compound;
3057 compound->modifiers |= modifiers;
3061 static void parse_enum_entries(type_t *const enum_type)
3065 if (token.type == '}') {
3066 errorf(HERE, "empty enum not allowed");
3071 add_anchor_token('}');
3073 if (token.type != T_IDENTIFIER) {
3074 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3076 rem_anchor_token('}');
3080 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3081 entity->enum_value.enum_type = enum_type;
3082 entity->base.symbol = token.v.symbol;
3083 entity->base.source_position = token.source_position;
3086 if (token.type == '=') {
3088 expression_t *value = parse_constant_expression();
3090 value = create_implicit_cast(value, enum_type);
3091 entity->enum_value.value = value;
3096 record_entity(entity, false);
3098 if (token.type != ',')
3101 } while (token.type != '}');
3102 rem_anchor_token('}');
3104 expect('}', end_error);
3110 static type_t *parse_enum_specifier(void)
3112 gnu_attribute_t *attributes = NULL;
3117 if (token.type == T_IDENTIFIER) {
3118 symbol = token.v.symbol;
3121 entity = get_entity(symbol, NAMESPACE_ENUM);
3122 if (entity != NULL) {
3123 assert(entity->kind == ENTITY_ENUM);
3124 if (entity->base.parent_scope != current_scope &&
3125 (token.type == '{' || token.type == ';')) {
3126 /* we're in an inner scope and have a definition. Shadow
3127 * existing definition in outer scope */
3129 } else if (entity->enume.complete && token.type == '{') {
3130 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3131 symbol, &entity->base.source_position);
3134 } else if (token.type != '{') {
3135 parse_error_expected("while parsing enum type specifier",
3136 T_IDENTIFIER, '{', NULL);
3143 if (entity == NULL) {
3144 entity = allocate_entity_zero(ENTITY_ENUM);
3145 entity->base.namespc = NAMESPACE_ENUM;
3146 entity->base.source_position = token.source_position;
3147 entity->base.symbol = symbol;
3148 entity->base.parent_scope = current_scope;
3151 type_t *const type = allocate_type_zero(TYPE_ENUM);
3152 type->enumt.enume = &entity->enume;
3153 type->enumt.akind = ATOMIC_TYPE_INT;
3155 if (token.type == '{') {
3156 if (symbol != NULL) {
3157 environment_push(entity);
3159 append_entity(current_scope, entity);
3160 entity->enume.complete = true;
3162 parse_enum_entries(type);
3163 parse_attributes(&attributes);
3165 if (symbol == NULL) {
3166 assert(anonymous_entity == NULL);
3167 anonymous_entity = entity;
3169 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3170 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3178 * if a symbol is a typedef to another type, return true
3180 static bool is_typedef_symbol(symbol_t *symbol)
3182 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3183 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3186 static type_t *parse_typeof(void)
3192 expect('(', end_error);
3193 add_anchor_token(')');
3195 expression_t *expression = NULL;
3197 bool old_type_prop = in_type_prop;
3198 bool old_gcc_extension = in_gcc_extension;
3199 in_type_prop = true;
3201 while (token.type == T___extension__) {
3202 /* This can be a prefix to a typename or an expression. */
3204 in_gcc_extension = true;
3206 switch (token.type) {
3208 if (is_typedef_symbol(token.v.symbol)) {
3209 type = parse_typename();
3211 expression = parse_expression();
3212 type = revert_automatic_type_conversion(expression);
3217 type = parse_typename();
3221 expression = parse_expression();
3222 type = expression->base.type;
3225 in_type_prop = old_type_prop;
3226 in_gcc_extension = old_gcc_extension;
3228 rem_anchor_token(')');
3229 expect(')', end_error);
3231 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3232 typeof_type->typeoft.expression = expression;
3233 typeof_type->typeoft.typeof_type = type;
3240 typedef enum specifiers_t {
3241 SPECIFIER_SIGNED = 1 << 0,
3242 SPECIFIER_UNSIGNED = 1 << 1,
3243 SPECIFIER_LONG = 1 << 2,
3244 SPECIFIER_INT = 1 << 3,
3245 SPECIFIER_DOUBLE = 1 << 4,
3246 SPECIFIER_CHAR = 1 << 5,
3247 SPECIFIER_WCHAR_T = 1 << 6,
3248 SPECIFIER_SHORT = 1 << 7,
3249 SPECIFIER_LONG_LONG = 1 << 8,
3250 SPECIFIER_FLOAT = 1 << 9,
3251 SPECIFIER_BOOL = 1 << 10,
3252 SPECIFIER_VOID = 1 << 11,
3253 SPECIFIER_INT8 = 1 << 12,
3254 SPECIFIER_INT16 = 1 << 13,
3255 SPECIFIER_INT32 = 1 << 14,
3256 SPECIFIER_INT64 = 1 << 15,
3257 SPECIFIER_INT128 = 1 << 16,
3258 SPECIFIER_COMPLEX = 1 << 17,
3259 SPECIFIER_IMAGINARY = 1 << 18,
3262 static type_t *create_builtin_type(symbol_t *const symbol,
3263 type_t *const real_type)
3265 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3266 type->builtin.symbol = symbol;
3267 type->builtin.real_type = real_type;
3268 return identify_new_type(type);
3271 static type_t *get_typedef_type(symbol_t *symbol)
3273 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3274 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3277 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3278 type->typedeft.typedefe = &entity->typedefe;
3284 * check for the allowed MS alignment values.
3286 static bool check_alignment_value(long long intvalue)
3288 if (intvalue < 1 || intvalue > 8192) {
3289 errorf(HERE, "illegal alignment value");
3292 unsigned v = (unsigned)intvalue;
3293 for (unsigned i = 1; i <= 8192; i += i) {
3297 errorf(HERE, "alignment must be power of two");
3301 #define DET_MOD(name, tag) do { \
3302 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3303 *modifiers |= tag; \
3306 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3308 decl_modifiers_t *modifiers = &specifiers->modifiers;
3311 if (token.type == T_restrict) {
3313 DET_MOD(restrict, DM_RESTRICT);
3315 } else if (token.type != T_IDENTIFIER)
3317 symbol_t *symbol = token.v.symbol;
3318 if (symbol == sym_align) {
3320 expect('(', end_error);
3321 if (token.type != T_INTEGER)
3323 if (check_alignment_value(token.v.intvalue)) {
3324 if (specifiers->alignment != 0 && warning.other)
3325 warningf(HERE, "align used more than once");
3326 specifiers->alignment = (unsigned char)token.v.intvalue;
3329 expect(')', end_error);
3330 } else if (symbol == sym_allocate) {
3332 expect('(', end_error);
3333 if (token.type != T_IDENTIFIER)
3335 (void)token.v.symbol;
3336 expect(')', end_error);
3337 } else if (symbol == sym_dllimport) {
3339 DET_MOD(dllimport, DM_DLLIMPORT);
3340 } else if (symbol == sym_dllexport) {
3342 DET_MOD(dllexport, DM_DLLEXPORT);
3343 } else if (symbol == sym_thread) {
3345 DET_MOD(thread, DM_THREAD);
3346 } else if (symbol == sym_naked) {
3348 DET_MOD(naked, DM_NAKED);
3349 } else if (symbol == sym_noinline) {
3351 DET_MOD(noinline, DM_NOINLINE);
3352 } else if (symbol == sym_returns_twice) {
3354 DET_MOD(returns_twice, DM_RETURNS_TWICE);
3355 } else if (symbol == sym_noreturn) {
3357 DET_MOD(noreturn, DM_NORETURN);
3358 } else if (symbol == sym_nothrow) {
3360 DET_MOD(nothrow, DM_NOTHROW);
3361 } else if (symbol == sym_novtable) {
3363 DET_MOD(novtable, DM_NOVTABLE);
3364 } else if (symbol == sym_property) {
3366 expect('(', end_error);
3368 bool is_get = false;
3369 if (token.type != T_IDENTIFIER)
3371 if (token.v.symbol == sym_get) {
3373 } else if (token.v.symbol == sym_put) {
3375 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3379 expect('=', end_error);
3380 if (token.type != T_IDENTIFIER)
3383 if (specifiers->get_property_sym != NULL) {
3384 errorf(HERE, "get property name already specified");
3386 specifiers->get_property_sym = token.v.symbol;
3389 if (specifiers->put_property_sym != NULL) {
3390 errorf(HERE, "put property name already specified");
3392 specifiers->put_property_sym = token.v.symbol;
3396 if (token.type == ',') {
3402 expect(')', end_error);
3403 } else if (symbol == sym_selectany) {
3405 DET_MOD(selectany, DM_SELECTANY);
3406 } else if (symbol == sym_uuid) {
3408 expect('(', end_error);
3409 if (token.type != T_STRING_LITERAL)
3412 expect(')', end_error);
3413 } else if (symbol == sym_deprecated) {
3415 if (specifiers->deprecated != 0 && warning.other)
3416 warningf(HERE, "deprecated used more than once");
3417 specifiers->deprecated = true;
3418 if (token.type == '(') {
3420 if (token.type == T_STRING_LITERAL) {
3421 specifiers->deprecated_string = token.v.string.begin;
3424 errorf(HERE, "string literal expected");
3426 expect(')', end_error);
3428 } else if (symbol == sym_noalias) {
3430 DET_MOD(noalias, DM_NOALIAS);
3433 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3435 if (token.type == '(')
3439 if (token.type == ',')
3446 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3448 entity_t *entity = allocate_entity_zero(kind);
3449 entity->base.source_position = *HERE;
3450 entity->base.symbol = symbol;
3451 if (is_declaration(entity)) {
3452 entity->declaration.type = type_error_type;
3453 entity->declaration.implicit = true;
3454 } else if (kind == ENTITY_TYPEDEF) {
3455 entity->typedefe.type = type_error_type;
3456 entity->typedefe.builtin = true;
3458 if (kind != ENTITY_COMPOUND_MEMBER)
3459 record_entity(entity, false);
3463 static void parse_microsoft_based(based_spec_t *based_spec)
3465 if (token.type != T_IDENTIFIER) {
3466 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3469 symbol_t *symbol = token.v.symbol;
3470 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3472 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3473 errorf(HERE, "'%Y' is not a variable name.", symbol);
3474 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3476 variable_t *variable = &entity->variable;
3478 if (based_spec->base_variable != NULL) {
3479 errorf(HERE, "__based type qualifier specified more than once");
3481 based_spec->source_position = token.source_position;
3482 based_spec->base_variable = variable;
3484 type_t *const type = variable->base.type;
3486 if (is_type_valid(type)) {
3487 if (! is_type_pointer(skip_typeref(type))) {
3488 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3490 if (variable->base.base.parent_scope != file_scope) {
3491 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3499 * Finish the construction of a struct type by calculating
3500 * its size, offsets, alignment.
3502 static void finish_struct_type(compound_type_t *type)
3504 assert(type->compound != NULL);
3506 compound_t *compound = type->compound;
3507 if (!compound->complete)
3512 il_alignment_t alignment = 1;
3513 bool need_pad = false;
3515 entity_t *entry = compound->members.entities;
3516 for (; entry != NULL; entry = entry->base.next) {
3517 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3520 type_t *m_type = skip_typeref(entry->declaration.type);
3521 if (! is_type_valid(m_type)) {
3522 /* simply ignore errors here */
3525 il_alignment_t m_alignment = m_type->base.alignment;
3526 if (m_alignment > alignment)
3527 alignment = m_alignment;
3529 offset = (size + m_alignment - 1) & -m_alignment;
3533 entry->compound_member.offset = offset;
3534 size = offset + m_type->base.size;
3536 if (type->base.alignment != 0) {
3537 alignment = type->base.alignment;
3540 offset = (size + alignment - 1) & -alignment;
3545 if (warning.padded) {
3546 warningf(&compound->base.source_position, "'%T' needs padding", type);
3549 if (compound->modifiers & DM_PACKED && warning.packed) {
3550 warningf(&compound->base.source_position,
3551 "superfluous packed attribute on '%T'", type);
3555 type->base.size = offset;
3556 type->base.alignment = alignment;
3560 * Finish the construction of an union type by calculating
3561 * its size and alignment.
3563 static void finish_union_type(compound_type_t *type)
3565 assert(type->compound != NULL);
3567 compound_t *compound = type->compound;
3568 if (! compound->complete)
3572 il_alignment_t alignment = 1;
3574 entity_t *entry = compound->members.entities;
3575 for (; entry != NULL; entry = entry->base.next) {
3576 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3579 type_t *m_type = skip_typeref(entry->declaration.type);
3580 if (! is_type_valid(m_type))
3583 entry->compound_member.offset = 0;
3584 if (m_type->base.size > size)
3585 size = m_type->base.size;
3586 if (m_type->base.alignment > alignment)
3587 alignment = m_type->base.alignment;
3589 if (type->base.alignment != 0) {
3590 alignment = type->base.alignment;
3592 size = (size + alignment - 1) & -alignment;
3593 type->base.size = size;
3594 type->base.alignment = alignment;
3597 static type_t *handle_attribute_mode(const gnu_attribute_t *attribute,
3600 type_t *type = skip_typeref(orig_type);
3602 /* at least: byte, word, pointer, list of machine modes
3603 * __XXX___ is interpreted as XXX */
3605 /* This isn't really correct, the backend should provide a list of machine
3606 * specific modes (according to gcc philosophy that is...) */
3607 const char *symbol_str = attribute->u.symbol->string;
3608 bool sign = is_type_signed(type);
3609 atomic_type_kind_t akind;
3610 if (strcmp_underscore("QI", symbol_str) == 0 ||
3611 strcmp_underscore("byte", symbol_str) == 0) {
3612 akind = sign ? ATOMIC_TYPE_CHAR : ATOMIC_TYPE_UCHAR;
3613 } else if (strcmp_underscore("HI", symbol_str) == 0) {
3614 akind = sign ? ATOMIC_TYPE_SHORT : ATOMIC_TYPE_USHORT;
3615 } else if (strcmp_underscore("SI", symbol_str) == 0
3616 || strcmp_underscore("word", symbol_str) == 0
3617 || strcmp_underscore("pointer", symbol_str) == 0) {
3618 akind = sign ? ATOMIC_TYPE_INT : ATOMIC_TYPE_UINT;
3619 } else if (strcmp_underscore("DI", symbol_str) == 0) {
3620 akind = sign ? ATOMIC_TYPE_LONGLONG : ATOMIC_TYPE_ULONGLONG;
3623 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
3627 if (type->kind == TYPE_ATOMIC) {
3628 type_t *copy = duplicate_type(type);
3629 copy->atomic.akind = akind;
3630 return identify_new_type(copy);
3631 } else if (type->kind == TYPE_ENUM) {
3632 type_t *copy = duplicate_type(type);
3633 copy->enumt.akind = akind;
3634 return identify_new_type(copy);
3635 } else if (is_type_pointer(type)) {
3636 warningf(HERE, "__attribute__((mode)) on pointers not implemented yet (ignored)");
3640 errorf(HERE, "__attribute__((mode)) only allowed on integer, enum or pointer type");
3644 static type_t *handle_type_attributes(const gnu_attribute_t *attributes,
3647 const gnu_attribute_t *attribute = attributes;
3648 for ( ; attribute != NULL; attribute = attribute->next) {
3649 if (attribute->invalid)
3652 if (attribute->kind == GNU_AK_MODE) {
3653 type = handle_attribute_mode(attribute, type);
3654 } else if (attribute->kind == GNU_AK_ALIGNED) {
3655 int alignment = 32; /* TODO: fill in maximum useful alignment for
3657 if (attribute->has_arguments)
3658 alignment = attribute->u.argument;
3660 type_t *copy = duplicate_type(type);
3661 copy->base.alignment = attribute->u.argument;
3662 type = identify_new_type(copy);
3669 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3671 type_t *type = NULL;
3672 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3673 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3674 unsigned type_specifiers = 0;
3675 bool newtype = false;
3676 bool saw_error = false;
3677 bool old_gcc_extension = in_gcc_extension;
3679 specifiers->source_position = token.source_position;
3682 specifiers->modifiers
3683 |= parse_attributes(&specifiers->gnu_attributes);
3685 switch (token.type) {
3687 #define MATCH_STORAGE_CLASS(token, class) \
3689 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3690 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3692 specifiers->storage_class = class; \
3693 if (specifiers->thread_local) \
3694 goto check_thread_storage_class; \
3698 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3699 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3700 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3701 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3702 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3706 expect('(', end_error);
3707 add_anchor_token(')');
3708 parse_microsoft_extended_decl_modifier(specifiers);
3709 rem_anchor_token(')');
3710 expect(')', end_error);
3714 if (specifiers->thread_local) {
3715 errorf(HERE, "duplicate '__thread'");
3717 specifiers->thread_local = true;
3718 check_thread_storage_class:
3719 switch (specifiers->storage_class) {
3720 case STORAGE_CLASS_EXTERN:
3721 case STORAGE_CLASS_NONE:
3722 case STORAGE_CLASS_STATIC:
3726 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3727 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3728 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3729 wrong_thread_stoarge_class:
3730 errorf(HERE, "'__thread' used with '%s'", wrong);
3737 /* type qualifiers */
3738 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3740 qualifiers |= qualifier; \
3744 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3745 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3746 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3747 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3748 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3749 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3750 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3751 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3753 case T___extension__:
3755 in_gcc_extension = true;
3758 /* type specifiers */
3759 #define MATCH_SPECIFIER(token, specifier, name) \
3761 if (type_specifiers & specifier) { \
3762 errorf(HERE, "multiple " name " type specifiers given"); \
3764 type_specifiers |= specifier; \
3769 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3770 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3771 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3772 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3773 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3774 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3775 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3776 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3777 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3778 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3779 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3780 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3781 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3782 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3783 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3784 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3785 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3786 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3788 case T__forceinline:
3789 /* only in microsoft mode */
3790 specifiers->modifiers |= DM_FORCEINLINE;
3795 specifiers->is_inline = true;
3799 if (type_specifiers & SPECIFIER_LONG_LONG) {
3800 errorf(HERE, "multiple type specifiers given");
3801 } else if (type_specifiers & SPECIFIER_LONG) {
3802 type_specifiers |= SPECIFIER_LONG_LONG;
3804 type_specifiers |= SPECIFIER_LONG;
3810 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3812 type->compound.compound = parse_compound_type_specifier(true);
3813 finish_struct_type(&type->compound);
3817 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3818 type->compound.compound = parse_compound_type_specifier(false);
3819 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3820 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3821 finish_union_type(&type->compound);
3825 type = parse_enum_specifier();
3828 type = parse_typeof();
3830 case T___builtin_va_list:
3831 type = duplicate_type(type_valist);
3835 case T_IDENTIFIER: {
3836 /* only parse identifier if we haven't found a type yet */
3837 if (type != NULL || type_specifiers != 0) {
3838 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3839 * declaration, so it doesn't generate errors about expecting '(' or
3841 switch (look_ahead(1)->type) {
3848 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3852 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3857 goto finish_specifiers;
3861 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3862 if (typedef_type == NULL) {
3863 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3864 * declaration, so it doesn't generate 'implicit int' followed by more
3865 * errors later on. */
3866 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3872 errorf(HERE, "%K does not name a type", &token);
3875 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3877 type = allocate_type_zero(TYPE_TYPEDEF);
3878 type->typedeft.typedefe = &entity->typedefe;
3882 if (la1_type == '&' || la1_type == '*')
3883 goto finish_specifiers;
3888 goto finish_specifiers;
3893 type = typedef_type;
3897 /* function specifier */
3899 goto finish_specifiers;
3904 specifiers->modifiers
3905 |= parse_attributes(&specifiers->gnu_attributes);
3907 in_gcc_extension = old_gcc_extension;
3909 if (type == NULL || (saw_error && type_specifiers != 0)) {
3910 atomic_type_kind_t atomic_type;
3912 /* match valid basic types */
3913 switch (type_specifiers) {
3914 case SPECIFIER_VOID:
3915 atomic_type = ATOMIC_TYPE_VOID;
3917 case SPECIFIER_WCHAR_T:
3918 atomic_type = ATOMIC_TYPE_WCHAR_T;
3920 case SPECIFIER_CHAR:
3921 atomic_type = ATOMIC_TYPE_CHAR;
3923 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3924 atomic_type = ATOMIC_TYPE_SCHAR;
3926 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3927 atomic_type = ATOMIC_TYPE_UCHAR;
3929 case SPECIFIER_SHORT:
3930 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3931 case SPECIFIER_SHORT | SPECIFIER_INT:
3932 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3933 atomic_type = ATOMIC_TYPE_SHORT;
3935 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3936 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3937 atomic_type = ATOMIC_TYPE_USHORT;
3940 case SPECIFIER_SIGNED:
3941 case SPECIFIER_SIGNED | SPECIFIER_INT:
3942 atomic_type = ATOMIC_TYPE_INT;
3944 case SPECIFIER_UNSIGNED:
3945 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3946 atomic_type = ATOMIC_TYPE_UINT;
3948 case SPECIFIER_LONG:
3949 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3950 case SPECIFIER_LONG | SPECIFIER_INT:
3951 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3952 atomic_type = ATOMIC_TYPE_LONG;
3954 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3955 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3956 atomic_type = ATOMIC_TYPE_ULONG;
3959 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3960 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3961 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3962 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3964 atomic_type = ATOMIC_TYPE_LONGLONG;
3965 goto warn_about_long_long;
3967 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3968 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3970 atomic_type = ATOMIC_TYPE_ULONGLONG;
3971 warn_about_long_long:
3972 if (warning.long_long) {
3973 warningf(&specifiers->source_position,
3974 "ISO C90 does not support 'long long'");
3978 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3979 atomic_type = unsigned_int8_type_kind;
3982 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3983 atomic_type = unsigned_int16_type_kind;
3986 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3987 atomic_type = unsigned_int32_type_kind;
3990 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3991 atomic_type = unsigned_int64_type_kind;
3994 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3995 atomic_type = unsigned_int128_type_kind;
3998 case SPECIFIER_INT8:
3999 case SPECIFIER_SIGNED | SPECIFIER_INT8:
4000 atomic_type = int8_type_kind;
4003 case SPECIFIER_INT16:
4004 case SPECIFIER_SIGNED | SPECIFIER_INT16:
4005 atomic_type = int16_type_kind;
4008 case SPECIFIER_INT32:
4009 case SPECIFIER_SIGNED | SPECIFIER_INT32:
4010 atomic_type = int32_type_kind;
4013 case SPECIFIER_INT64:
4014 case SPECIFIER_SIGNED | SPECIFIER_INT64:
4015 atomic_type = int64_type_kind;
4018 case SPECIFIER_INT128:
4019 case SPECIFIER_SIGNED | SPECIFIER_INT128:
4020 atomic_type = int128_type_kind;
4023 case SPECIFIER_FLOAT:
4024 atomic_type = ATOMIC_TYPE_FLOAT;
4026 case SPECIFIER_DOUBLE:
4027 atomic_type = ATOMIC_TYPE_DOUBLE;
4029 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
4030 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4032 case SPECIFIER_BOOL:
4033 atomic_type = ATOMIC_TYPE_BOOL;
4035 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
4036 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
4037 atomic_type = ATOMIC_TYPE_FLOAT;
4039 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4040 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4041 atomic_type = ATOMIC_TYPE_DOUBLE;
4043 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
4044 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
4045 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
4048 /* invalid specifier combination, give an error message */
4049 if (type_specifiers == 0) {
4053 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
4054 if (!(c_mode & _CXX) && !strict_mode) {
4055 if (warning.implicit_int) {
4056 warningf(HERE, "no type specifiers in declaration, using 'int'");
4058 atomic_type = ATOMIC_TYPE_INT;
4061 errorf(HERE, "no type specifiers given in declaration");
4063 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4064 (type_specifiers & SPECIFIER_UNSIGNED)) {
4065 errorf(HERE, "signed and unsigned specifiers given");
4066 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4067 errorf(HERE, "only integer types can be signed or unsigned");
4069 errorf(HERE, "multiple datatypes in declaration");
4074 if (type_specifiers & SPECIFIER_COMPLEX) {
4075 type = allocate_type_zero(TYPE_COMPLEX);
4076 type->complex.akind = atomic_type;
4077 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4078 type = allocate_type_zero(TYPE_IMAGINARY);
4079 type->imaginary.akind = atomic_type;
4081 type = allocate_type_zero(TYPE_ATOMIC);
4082 type->atomic.akind = atomic_type;
4084 type->base.alignment = get_atomic_type_alignment(atomic_type);
4085 unsigned const size = get_atomic_type_size(atomic_type);
4087 type_specifiers & SPECIFIER_COMPLEX ? size * 2 : size;
4089 } else if (type_specifiers != 0) {
4090 errorf(HERE, "multiple datatypes in declaration");
4093 /* FIXME: check type qualifiers here */
4095 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
4096 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4097 type->base.qualifiers = qualifiers;
4098 type->base.modifiers = modifiers;
4101 type = identify_new_type(type);
4103 type = typehash_insert(type);
4106 type = handle_type_attributes(specifiers->gnu_attributes, type);
4107 specifiers->type = type;
4111 specifiers->type = type_error_type;
4115 static type_qualifiers_t parse_type_qualifiers(void)
4117 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4120 switch (token.type) {
4121 /* type qualifiers */
4122 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4123 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4124 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4125 /* microsoft extended type modifiers */
4126 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4127 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4128 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4129 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4130 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4139 * Parses an K&R identifier list
4141 static void parse_identifier_list(scope_t *scope)
4144 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4145 entity->base.source_position = token.source_position;
4146 entity->base.namespc = NAMESPACE_NORMAL;
4147 entity->base.symbol = token.v.symbol;
4148 /* a K&R parameter has no type, yet */
4152 append_entity(scope, entity);
4154 if (token.type != ',') {
4158 } while (token.type == T_IDENTIFIER);
4161 static entity_t *parse_parameter(void)
4163 declaration_specifiers_t specifiers;
4164 memset(&specifiers, 0, sizeof(specifiers));
4166 parse_declaration_specifiers(&specifiers);
4168 entity_t *entity = parse_declarator(&specifiers,
4169 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4170 anonymous_entity = NULL;
4174 static void semantic_parameter_incomplete(const entity_t *entity)
4176 assert(entity->kind == ENTITY_PARAMETER);
4178 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4179 * list in a function declarator that is part of a
4180 * definition of that function shall not have
4181 * incomplete type. */
4182 type_t *type = skip_typeref(entity->declaration.type);
4183 if (is_type_incomplete(type)) {
4184 errorf(&entity->base.source_position,
4185 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4186 entity->declaration.type);
4191 * Parses function type parameters (and optionally creates variable_t entities
4192 * for them in a scope)
4194 static void parse_parameters(function_type_t *type, scope_t *scope)
4197 add_anchor_token(')');
4198 int saved_comma_state = save_and_reset_anchor_state(',');
4200 if (token.type == T_IDENTIFIER &&
4201 !is_typedef_symbol(token.v.symbol)) {
4202 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4203 if (la1_type == ',' || la1_type == ')') {
4204 type->kr_style_parameters = true;
4205 type->unspecified_parameters = true;
4206 parse_identifier_list(scope);
4207 goto parameters_finished;
4211 if (token.type == ')') {
4212 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4213 if (!(c_mode & _CXX))
4214 type->unspecified_parameters = true;
4215 goto parameters_finished;
4218 function_parameter_t *parameter;
4219 function_parameter_t *last_parameter = NULL;
4222 switch (token.type) {
4225 type->variadic = true;
4226 goto parameters_finished;
4229 case T___extension__:
4232 entity_t *entity = parse_parameter();
4233 if (entity->kind == ENTITY_TYPEDEF) {
4234 errorf(&entity->base.source_position,
4235 "typedef not allowed as function parameter");
4238 assert(is_declaration(entity));
4240 /* func(void) is not a parameter */
4241 if (last_parameter == NULL
4242 && token.type == ')'
4243 && entity->base.symbol == NULL
4244 && skip_typeref(entity->declaration.type) == type_void) {
4245 goto parameters_finished;
4247 semantic_parameter_incomplete(entity);
4249 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4250 memset(parameter, 0, sizeof(parameter[0]));
4251 parameter->type = entity->declaration.type;
4253 if (scope != NULL) {
4254 append_entity(scope, entity);
4257 if (last_parameter != NULL) {
4258 last_parameter->next = parameter;
4260 type->parameters = parameter;
4262 last_parameter = parameter;
4267 goto parameters_finished;
4269 if (token.type != ',') {
4270 goto parameters_finished;
4276 parameters_finished:
4277 rem_anchor_token(')');
4278 expect(')', end_error);
4281 restore_anchor_state(',', saved_comma_state);
4284 typedef enum construct_type_kind_t {
4287 CONSTRUCT_REFERENCE,
4290 } construct_type_kind_t;
4292 typedef struct construct_type_t construct_type_t;
4293 struct construct_type_t {
4294 construct_type_kind_t kind;
4295 construct_type_t *next;
4298 typedef struct parsed_pointer_t parsed_pointer_t;
4299 struct parsed_pointer_t {
4300 construct_type_t construct_type;
4301 type_qualifiers_t type_qualifiers;
4302 variable_t *base_variable; /**< MS __based extension. */
4305 typedef struct parsed_reference_t parsed_reference_t;
4306 struct parsed_reference_t {
4307 construct_type_t construct_type;
4310 typedef struct construct_function_type_t construct_function_type_t;
4311 struct construct_function_type_t {
4312 construct_type_t construct_type;
4313 type_t *function_type;
4316 typedef struct parsed_array_t parsed_array_t;
4317 struct parsed_array_t {
4318 construct_type_t construct_type;
4319 type_qualifiers_t type_qualifiers;
4325 typedef struct construct_base_type_t construct_base_type_t;
4326 struct construct_base_type_t {
4327 construct_type_t construct_type;
4331 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4335 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4336 memset(pointer, 0, sizeof(pointer[0]));
4337 pointer->construct_type.kind = CONSTRUCT_POINTER;
4338 pointer->type_qualifiers = parse_type_qualifiers();
4339 pointer->base_variable = base_variable;
4341 return &pointer->construct_type;
4344 static construct_type_t *parse_reference_declarator(void)
4348 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4349 memset(reference, 0, sizeof(reference[0]));
4350 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4352 return (construct_type_t*)reference;
4355 static construct_type_t *parse_array_declarator(void)
4358 add_anchor_token(']');
4360 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4361 memset(array, 0, sizeof(array[0]));
4362 array->construct_type.kind = CONSTRUCT_ARRAY;
4364 if (token.type == T_static) {
4365 array->is_static = true;
4369 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4370 if (type_qualifiers != 0) {
4371 if (token.type == T_static) {
4372 array->is_static = true;
4376 array->type_qualifiers = type_qualifiers;
4378 if (token.type == '*' && look_ahead(1)->type == ']') {
4379 array->is_variable = true;
4381 } else if (token.type != ']') {
4382 expression_t *const size = parse_assignment_expression();
4384 mark_vars_read(size, NULL);
4387 rem_anchor_token(']');
4388 expect(']', end_error);
4391 return &array->construct_type;
4394 static construct_type_t *parse_function_declarator(scope_t *scope,
4395 decl_modifiers_t modifiers)
4397 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4398 function_type_t *ftype = &type->function;
4400 ftype->linkage = current_linkage;
4402 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4403 case DM_NONE: break;
4404 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4405 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4406 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4407 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4410 errorf(HERE, "multiple calling conventions in declaration");
4414 parse_parameters(ftype, scope);
4416 construct_function_type_t *construct_function_type =
4417 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4418 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4419 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4420 construct_function_type->function_type = type;
4422 return &construct_function_type->construct_type;
4425 typedef struct parse_declarator_env_t {
4426 decl_modifiers_t modifiers;
4428 source_position_t source_position;
4430 } parse_declarator_env_t;
4432 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4433 bool may_be_abstract)
4435 /* construct a single linked list of construct_type_t's which describe
4436 * how to construct the final declarator type */
4437 construct_type_t *first = NULL;
4438 construct_type_t *last = NULL;
4439 gnu_attribute_t *attributes = NULL;
4441 decl_modifiers_t modifiers = parse_attributes(&attributes);
4443 /* MS __based extension */
4444 based_spec_t base_spec;
4445 base_spec.base_variable = NULL;
4448 construct_type_t *type;
4449 switch (token.type) {
4451 if (!(c_mode & _CXX))
4452 errorf(HERE, "references are only available for C++");
4453 if (base_spec.base_variable != NULL && warning.other) {
4454 warningf(&base_spec.source_position,
4455 "__based does not precede a pointer operator, ignored");
4457 type = parse_reference_declarator();
4459 base_spec.base_variable = NULL;
4463 type = parse_pointer_declarator(base_spec.base_variable);
4465 base_spec.base_variable = NULL;
4470 expect('(', end_error);
4471 add_anchor_token(')');
4472 parse_microsoft_based(&base_spec);
4473 rem_anchor_token(')');
4474 expect(')', end_error);
4478 goto ptr_operator_end;
4489 /* TODO: find out if this is correct */
4490 modifiers |= parse_attributes(&attributes);
4493 if (base_spec.base_variable != NULL && warning.other) {
4494 warningf(&base_spec.source_position,
4495 "__based does not precede a pointer operator, ignored");
4499 modifiers |= env->modifiers;
4500 env->modifiers = modifiers;
4503 construct_type_t *inner_types = NULL;
4505 switch (token.type) {
4508 errorf(HERE, "no identifier expected in typename");
4510 env->symbol = token.v.symbol;
4511 env->source_position = token.source_position;
4516 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
4517 * interpreted as ``function with no parameter specification'', rather
4518 * than redundant parentheses around the omitted identifier. */
4519 if (look_ahead(1)->type != ')') {
4521 add_anchor_token(')');
4522 inner_types = parse_inner_declarator(env, may_be_abstract);
4523 if (inner_types != NULL) {
4524 /* All later declarators only modify the return type */
4527 rem_anchor_token(')');
4528 expect(')', end_error);
4532 if (may_be_abstract)
4534 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4539 construct_type_t *p = last;
4542 construct_type_t *type;
4543 switch (token.type) {
4545 scope_t *scope = NULL;
4547 scope = &env->parameters;
4549 type = parse_function_declarator(scope, modifiers);
4553 type = parse_array_declarator();
4556 goto declarator_finished;
4559 /* insert in the middle of the list (behind p) */
4561 type->next = p->next;
4572 declarator_finished:
4573 /* append inner_types at the end of the list, we don't to set last anymore
4574 * as it's not needed anymore */
4576 assert(first == NULL);
4577 first = inner_types;
4579 last->next = inner_types;
4587 static void parse_declaration_attributes(entity_t *entity)
4589 gnu_attribute_t *attributes = NULL;
4590 decl_modifiers_t modifiers = parse_attributes(&attributes);
4596 if (entity->kind == ENTITY_TYPEDEF) {
4597 modifiers |= entity->typedefe.modifiers;
4598 type = entity->typedefe.type;
4600 assert(is_declaration(entity));
4601 modifiers |= entity->declaration.modifiers;
4602 type = entity->declaration.type;
4607 gnu_attribute_t *attribute = attributes;
4608 for ( ; attribute != NULL; attribute = attribute->next) {
4609 if (attribute->invalid)
4612 if (attribute->kind == GNU_AK_MODE) {
4613 type = handle_attribute_mode(attribute, type);
4614 } else if (attribute->kind == GNU_AK_ALIGNED) {
4615 int alignment = 32; /* TODO: fill in maximum usefull alignment for target machine */
4616 if (attribute->has_arguments)
4617 alignment = attribute->u.argument;
4619 if (entity->kind == ENTITY_TYPEDEF) {
4620 type_t *copy = duplicate_type(type);
4621 copy->base.alignment = attribute->u.argument;
4622 type = identify_new_type(copy);
4623 } else if(entity->kind == ENTITY_VARIABLE) {
4624 entity->variable.alignment = alignment;
4625 } else if(entity->kind == ENTITY_COMPOUND_MEMBER) {
4626 entity->compound_member.alignment = alignment;
4631 type_modifiers_t type_modifiers = type->base.modifiers;
4632 if (modifiers & DM_TRANSPARENT_UNION)
4633 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4635 if (type->base.modifiers != type_modifiers) {
4636 type_t *copy = duplicate_type(type);
4637 copy->base.modifiers = type_modifiers;
4638 type = identify_new_type(copy);
4641 if (entity->kind == ENTITY_TYPEDEF) {
4642 entity->typedefe.type = type;
4643 entity->typedefe.modifiers = modifiers;
4645 entity->declaration.type = type;
4646 entity->declaration.modifiers = modifiers;
4650 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4652 construct_type_t *iter = construct_list;
4653 for (; iter != NULL; iter = iter->next) {
4654 switch (iter->kind) {
4655 case CONSTRUCT_INVALID:
4656 internal_errorf(HERE, "invalid type construction found");
4657 case CONSTRUCT_FUNCTION: {
4658 construct_function_type_t *construct_function_type
4659 = (construct_function_type_t*) iter;
4661 type_t *function_type = construct_function_type->function_type;
4663 function_type->function.return_type = type;
4665 type_t *skipped_return_type = skip_typeref(type);
4667 if (is_type_function(skipped_return_type)) {
4668 errorf(HERE, "function returning function is not allowed");
4669 } else if (is_type_array(skipped_return_type)) {
4670 errorf(HERE, "function returning array is not allowed");
4672 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4674 "type qualifiers in return type of function type are meaningless");
4678 type = function_type;
4682 case CONSTRUCT_POINTER: {
4683 if (is_type_reference(skip_typeref(type)))
4684 errorf(HERE, "cannot declare a pointer to reference");
4686 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4687 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4691 case CONSTRUCT_REFERENCE:
4692 if (is_type_reference(skip_typeref(type)))
4693 errorf(HERE, "cannot declare a reference to reference");
4695 type = make_reference_type(type);
4698 case CONSTRUCT_ARRAY: {
4699 if (is_type_reference(skip_typeref(type)))
4700 errorf(HERE, "cannot declare an array of references");
4702 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4703 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4705 expression_t *size_expression = parsed_array->size;
4706 if (size_expression != NULL) {
4708 = create_implicit_cast(size_expression, type_size_t);
4711 array_type->base.qualifiers = parsed_array->type_qualifiers;
4712 array_type->array.element_type = type;
4713 array_type->array.is_static = parsed_array->is_static;
4714 array_type->array.is_variable = parsed_array->is_variable;
4715 array_type->array.size_expression = size_expression;
4717 if (size_expression != NULL) {
4718 if (is_constant_expression(size_expression)) {
4719 array_type->array.size_constant = true;
4720 array_type->array.size
4721 = fold_constant(size_expression);
4723 array_type->array.is_vla = true;
4727 type_t *skipped_type = skip_typeref(type);
4729 if (is_type_incomplete(skipped_type)) {
4730 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4731 } else if (is_type_function(skipped_type)) {
4732 errorf(HERE, "array of functions is not allowed");
4739 /* The function type was constructed earlier. Freeing it here will
4740 * destroy other types. */
4741 if (iter->kind == CONSTRUCT_FUNCTION) {
4742 type = typehash_insert(type);
4744 type = identify_new_type(type);
4751 static type_t *automatic_type_conversion(type_t *orig_type);
4753 static type_t *semantic_parameter(const source_position_t *pos,
4755 const declaration_specifiers_t *specifiers,
4758 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4759 * shall be adjusted to ``qualified pointer to type'',
4761 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4762 * type'' shall be adjusted to ``pointer to function
4763 * returning type'', as in 6.3.2.1. */
4764 type = automatic_type_conversion(type);
4766 if (specifiers->is_inline && is_type_valid(type)) {
4767 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4770 /* §6.9.1:6 The declarations in the declaration list shall contain
4771 * no storage-class specifier other than register and no
4772 * initializations. */
4773 if (specifiers->thread_local || (
4774 specifiers->storage_class != STORAGE_CLASS_NONE &&
4775 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4777 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4780 /* delay test for incomplete type, because we might have (void)
4781 * which is legal but incomplete... */
4786 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4787 declarator_flags_t flags)
4789 parse_declarator_env_t env;
4790 memset(&env, 0, sizeof(env));
4791 env.modifiers = specifiers->modifiers;
4793 construct_type_t *construct_type =
4794 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4796 construct_declarator_type(construct_type, specifiers->type);
4797 type_t *type = skip_typeref(orig_type);
4799 if (construct_type != NULL) {
4800 obstack_free(&temp_obst, construct_type);
4804 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4805 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4806 entity->base.symbol = env.symbol;
4807 entity->base.source_position = env.source_position;
4808 entity->typedefe.type = orig_type;
4810 if (anonymous_entity != NULL) {
4811 if (is_type_compound(type)) {
4812 assert(anonymous_entity->compound.alias == NULL);
4813 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4814 anonymous_entity->kind == ENTITY_UNION);
4815 anonymous_entity->compound.alias = entity;
4816 anonymous_entity = NULL;
4817 } else if (is_type_enum(type)) {
4818 assert(anonymous_entity->enume.alias == NULL);
4819 assert(anonymous_entity->kind == ENTITY_ENUM);
4820 anonymous_entity->enume.alias = entity;
4821 anonymous_entity = NULL;
4825 /* create a declaration type entity */
4826 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4827 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4829 if (env.symbol != NULL) {
4830 if (specifiers->is_inline && is_type_valid(type)) {
4831 errorf(&env.source_position,
4832 "compound member '%Y' declared 'inline'", env.symbol);
4835 if (specifiers->thread_local ||
4836 specifiers->storage_class != STORAGE_CLASS_NONE) {
4837 errorf(&env.source_position,
4838 "compound member '%Y' must have no storage class",
4842 } else if (flags & DECL_IS_PARAMETER) {
4843 orig_type = semantic_parameter(&env.source_position, orig_type,
4844 specifiers, env.symbol);
4846 entity = allocate_entity_zero(ENTITY_PARAMETER);
4847 } else if (is_type_function(type)) {
4848 entity = allocate_entity_zero(ENTITY_FUNCTION);
4850 entity->function.is_inline = specifiers->is_inline;
4851 entity->function.parameters = env.parameters;
4853 if (env.symbol != NULL) {
4854 if (specifiers->thread_local || (
4855 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4856 specifiers->storage_class != STORAGE_CLASS_NONE &&
4857 specifiers->storage_class != STORAGE_CLASS_STATIC
4859 errorf(&env.source_position,
4860 "invalid storage class for function '%Y'", env.symbol);
4864 entity = allocate_entity_zero(ENTITY_VARIABLE);
4866 entity->variable.get_property_sym = specifiers->get_property_sym;
4867 entity->variable.put_property_sym = specifiers->put_property_sym;
4869 entity->variable.thread_local = specifiers->thread_local;
4871 if (env.symbol != NULL) {
4872 if (specifiers->is_inline && is_type_valid(type)) {
4873 errorf(&env.source_position,
4874 "variable '%Y' declared 'inline'", env.symbol);
4877 bool invalid_storage_class = false;
4878 if (current_scope == file_scope) {
4879 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4880 specifiers->storage_class != STORAGE_CLASS_NONE &&
4881 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4882 invalid_storage_class = true;
4885 if (specifiers->thread_local &&
4886 specifiers->storage_class == STORAGE_CLASS_NONE) {
4887 invalid_storage_class = true;
4890 if (invalid_storage_class) {
4891 errorf(&env.source_position,
4892 "invalid storage class for variable '%Y'", env.symbol);
4897 if (env.symbol != NULL) {
4898 entity->base.symbol = env.symbol;
4899 entity->base.source_position = env.source_position;
4901 entity->base.source_position = specifiers->source_position;
4903 entity->base.namespc = NAMESPACE_NORMAL;
4904 entity->declaration.type = orig_type;
4905 entity->declaration.modifiers = env.modifiers;
4906 entity->declaration.deprecated_string = specifiers->deprecated_string;
4908 storage_class_t storage_class = specifiers->storage_class;
4909 entity->declaration.declared_storage_class = storage_class;
4911 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4912 storage_class = STORAGE_CLASS_AUTO;
4913 entity->declaration.storage_class = storage_class;
4916 parse_declaration_attributes(entity);
4921 static type_t *parse_abstract_declarator(type_t *base_type)
4923 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4925 type_t *result = construct_declarator_type(construct_type, base_type);
4926 if (construct_type != NULL) {
4927 obstack_free(&temp_obst, construct_type);
4934 * Check if the declaration of main is suspicious. main should be a
4935 * function with external linkage, returning int, taking either zero
4936 * arguments, two, or three arguments of appropriate types, ie.
4938 * int main([ int argc, char **argv [, char **env ] ]).
4940 * @param decl the declaration to check
4941 * @param type the function type of the declaration
4943 static void check_type_of_main(const entity_t *entity)
4945 const source_position_t *pos = &entity->base.source_position;
4946 if (entity->kind != ENTITY_FUNCTION) {
4947 warningf(pos, "'main' is not a function");
4951 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4952 warningf(pos, "'main' is normally a non-static function");
4955 type_t *type = skip_typeref(entity->declaration.type);
4956 assert(is_type_function(type));
4958 function_type_t *func_type = &type->function;
4959 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4960 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4961 func_type->return_type);
4963 const function_parameter_t *parm = func_type->parameters;
4965 type_t *const first_type = parm->type;
4966 if (!types_compatible(skip_typeref(first_type), type_int)) {
4968 "first argument of 'main' should be 'int', but is '%T'",
4973 type_t *const second_type = parm->type;
4974 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4975 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4979 type_t *const third_type = parm->type;
4980 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4981 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4985 goto warn_arg_count;
4989 warningf(pos, "'main' takes only zero, two or three arguments");
4995 * Check if a symbol is the equal to "main".
4997 static bool is_sym_main(const symbol_t *const sym)
4999 return strcmp(sym->string, "main") == 0;
5002 static void error_redefined_as_different_kind(const source_position_t *pos,
5003 const entity_t *old, entity_kind_t new_kind)
5005 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
5006 get_entity_kind_name(old->kind), old->base.symbol,
5007 get_entity_kind_name(new_kind), &old->base.source_position);
5010 static bool is_error_entity(entity_t *const ent)
5012 if (is_declaration(ent)) {
5013 return is_type_valid(skip_typeref(ent->declaration.type));
5014 } else if (ent->kind == ENTITY_TYPEDEF) {
5015 return is_type_valid(skip_typeref(ent->typedefe.type));
5021 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
5022 * for various problems that occur for multiple definitions
5024 static entity_t *record_entity(entity_t *entity, const bool is_definition)
5026 const symbol_t *const symbol = entity->base.symbol;
5027 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
5028 const source_position_t *pos = &entity->base.source_position;
5030 /* can happen in error cases */
5034 entity_t *const previous_entity = get_entity(symbol, namespc);
5035 /* pushing the same entity twice will break the stack structure */
5036 assert(previous_entity != entity);
5038 if (entity->kind == ENTITY_FUNCTION) {
5039 type_t *const orig_type = entity->declaration.type;
5040 type_t *const type = skip_typeref(orig_type);
5042 assert(is_type_function(type));
5043 if (type->function.unspecified_parameters &&
5044 warning.strict_prototypes &&
5045 previous_entity == NULL) {
5046 warningf(pos, "function declaration '%#T' is not a prototype",
5050 if (warning.main && current_scope == file_scope
5051 && is_sym_main(symbol)) {
5052 check_type_of_main(entity);
5056 if (is_declaration(entity) &&
5057 warning.nested_externs &&
5058 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
5059 current_scope != file_scope) {
5060 warningf(pos, "nested extern declaration of '%#T'",
5061 entity->declaration.type, symbol);
5064 if (previous_entity != NULL) {
5065 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
5066 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
5067 assert(previous_entity->kind == ENTITY_PARAMETER);
5069 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
5070 entity->declaration.type, symbol,
5071 previous_entity->declaration.type, symbol,
5072 &previous_entity->base.source_position);
5076 if (previous_entity->base.parent_scope == current_scope) {
5077 if (previous_entity->kind != entity->kind) {
5078 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
5079 error_redefined_as_different_kind(pos, previous_entity,
5084 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5085 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5086 symbol, &previous_entity->base.source_position);
5089 if (previous_entity->kind == ENTITY_TYPEDEF) {
5090 /* TODO: C++ allows this for exactly the same type */
5091 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5092 symbol, &previous_entity->base.source_position);
5096 /* at this point we should have only VARIABLES or FUNCTIONS */
5097 assert(is_declaration(previous_entity) && is_declaration(entity));
5099 declaration_t *const prev_decl = &previous_entity->declaration;
5100 declaration_t *const decl = &entity->declaration;
5102 /* can happen for K&R style declarations */
5103 if (prev_decl->type == NULL &&
5104 previous_entity->kind == ENTITY_PARAMETER &&
5105 entity->kind == ENTITY_PARAMETER) {
5106 prev_decl->type = decl->type;
5107 prev_decl->storage_class = decl->storage_class;
5108 prev_decl->declared_storage_class = decl->declared_storage_class;
5109 prev_decl->modifiers = decl->modifiers;
5110 prev_decl->deprecated_string = decl->deprecated_string;
5111 return previous_entity;
5114 type_t *const orig_type = decl->type;
5115 assert(orig_type != NULL);
5116 type_t *const type = skip_typeref(orig_type);
5117 type_t *const prev_type = skip_typeref(prev_decl->type);
5119 if (!types_compatible(type, prev_type)) {
5121 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5122 orig_type, symbol, prev_decl->type, symbol,
5123 &previous_entity->base.source_position);
5125 unsigned old_storage_class = prev_decl->storage_class;
5126 if (warning.redundant_decls &&
5129 !(prev_decl->modifiers & DM_USED) &&
5130 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5131 warningf(&previous_entity->base.source_position,
5132 "unnecessary static forward declaration for '%#T'",
5133 prev_decl->type, symbol);
5136 storage_class_t new_storage_class = decl->storage_class;
5138 /* pretend no storage class means extern for function
5139 * declarations (except if the previous declaration is neither
5140 * none nor extern) */
5141 if (entity->kind == ENTITY_FUNCTION) {
5142 /* the previous declaration could have unspecified parameters or
5143 * be a typedef, so use the new type */
5144 if (prev_type->function.unspecified_parameters || is_definition)
5145 prev_decl->type = type;
5147 switch (old_storage_class) {
5148 case STORAGE_CLASS_NONE:
5149 old_storage_class = STORAGE_CLASS_EXTERN;
5152 case STORAGE_CLASS_EXTERN:
5153 if (is_definition) {
5154 if (warning.missing_prototypes &&
5155 prev_type->function.unspecified_parameters &&
5156 !is_sym_main(symbol)) {
5157 warningf(pos, "no previous prototype for '%#T'",
5160 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5161 new_storage_class = STORAGE_CLASS_EXTERN;
5168 } else if (is_type_incomplete(prev_type)) {
5169 prev_decl->type = type;
5172 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5173 new_storage_class == STORAGE_CLASS_EXTERN) {
5174 warn_redundant_declaration:
5175 if (!is_definition &&
5176 warning.redundant_decls &&
5177 is_type_valid(prev_type) &&
5178 strcmp(previous_entity->base.source_position.input_name,
5179 "<builtin>") != 0) {
5181 "redundant declaration for '%Y' (declared %P)",
5182 symbol, &previous_entity->base.source_position);
5184 } else if (current_function == NULL) {
5185 if (old_storage_class != STORAGE_CLASS_STATIC &&
5186 new_storage_class == STORAGE_CLASS_STATIC) {
5188 "static declaration of '%Y' follows non-static declaration (declared %P)",
5189 symbol, &previous_entity->base.source_position);
5190 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5191 prev_decl->storage_class = STORAGE_CLASS_NONE;
5192 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5194 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5196 goto error_redeclaration;
5197 goto warn_redundant_declaration;
5199 } else if (is_type_valid(prev_type)) {
5200 if (old_storage_class == new_storage_class) {
5201 error_redeclaration:
5202 errorf(pos, "redeclaration of '%Y' (declared %P)",
5203 symbol, &previous_entity->base.source_position);
5206 "redeclaration of '%Y' with different linkage (declared %P)",
5207 symbol, &previous_entity->base.source_position);
5212 prev_decl->modifiers |= decl->modifiers;
5213 if (entity->kind == ENTITY_FUNCTION) {
5214 previous_entity->function.is_inline |= entity->function.is_inline;
5216 return previous_entity;
5219 if (warning.shadow) {
5220 warningf(pos, "%s '%Y' shadows %s (declared %P)",
5221 get_entity_kind_name(entity->kind), symbol,
5222 get_entity_kind_name(previous_entity->kind),
5223 &previous_entity->base.source_position);
5227 if (entity->kind == ENTITY_FUNCTION) {
5228 if (is_definition &&
5229 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5230 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5231 warningf(pos, "no previous prototype for '%#T'",
5232 entity->declaration.type, symbol);
5233 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5234 warningf(pos, "no previous declaration for '%#T'",
5235 entity->declaration.type, symbol);
5238 } else if (warning.missing_declarations &&
5239 entity->kind == ENTITY_VARIABLE &&
5240 current_scope == file_scope) {
5241 declaration_t *declaration = &entity->declaration;
5242 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5243 warningf(pos, "no previous declaration for '%#T'",
5244 declaration->type, symbol);
5249 assert(entity->base.parent_scope == NULL);
5250 assert(current_scope != NULL);
5252 entity->base.parent_scope = current_scope;
5253 entity->base.namespc = NAMESPACE_NORMAL;
5254 environment_push(entity);
5255 append_entity(current_scope, entity);
5260 static void parser_error_multiple_definition(entity_t *entity,
5261 const source_position_t *source_position)
5263 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5264 entity->base.symbol, &entity->base.source_position);
5267 static bool is_declaration_specifier(const token_t *token,
5268 bool only_specifiers_qualifiers)
5270 switch (token->type) {
5275 return is_typedef_symbol(token->v.symbol);
5277 case T___extension__:
5279 return !only_specifiers_qualifiers;
5286 static void parse_init_declarator_rest(entity_t *entity)
5288 assert(is_declaration(entity));
5289 declaration_t *const declaration = &entity->declaration;
5293 type_t *orig_type = declaration->type;
5294 type_t *type = skip_typeref(orig_type);
5296 if (entity->kind == ENTITY_VARIABLE
5297 && entity->variable.initializer != NULL) {
5298 parser_error_multiple_definition(entity, HERE);
5301 bool must_be_constant = false;
5302 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5303 entity->base.parent_scope == file_scope) {
5304 must_be_constant = true;
5307 if (is_type_function(type)) {
5308 errorf(&entity->base.source_position,
5309 "function '%#T' is initialized like a variable",
5310 orig_type, entity->base.symbol);
5311 orig_type = type_error_type;
5314 parse_initializer_env_t env;
5315 env.type = orig_type;
5316 env.must_be_constant = must_be_constant;
5317 env.entity = entity;
5318 current_init_decl = entity;
5320 initializer_t *initializer = parse_initializer(&env);
5321 current_init_decl = NULL;
5323 if (entity->kind == ENTITY_VARIABLE) {
5324 /* §6.7.5:22 array initializers for arrays with unknown size
5325 * determine the array type size */
5326 declaration->type = env.type;
5327 entity->variable.initializer = initializer;
5331 /* parse rest of a declaration without any declarator */
5332 static void parse_anonymous_declaration_rest(
5333 const declaration_specifiers_t *specifiers)
5336 anonymous_entity = NULL;
5338 if (warning.other) {
5339 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5340 specifiers->thread_local) {
5341 warningf(&specifiers->source_position,
5342 "useless storage class in empty declaration");
5345 type_t *type = specifiers->type;
5346 switch (type->kind) {
5347 case TYPE_COMPOUND_STRUCT:
5348 case TYPE_COMPOUND_UNION: {
5349 if (type->compound.compound->base.symbol == NULL) {
5350 warningf(&specifiers->source_position,
5351 "unnamed struct/union that defines no instances");
5360 warningf(&specifiers->source_position, "empty declaration");
5366 static void check_variable_type_complete(entity_t *ent)
5368 if (ent->kind != ENTITY_VARIABLE)
5371 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5372 * type for the object shall be complete [...] */
5373 declaration_t *decl = &ent->declaration;
5374 if (decl->storage_class != STORAGE_CLASS_NONE)
5377 type_t *const orig_type = decl->type;
5378 type_t *const type = skip_typeref(orig_type);
5379 if (!is_type_incomplete(type))
5382 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
5383 * are given length one. */
5384 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
5385 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5389 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5390 orig_type, ent->base.symbol);
5394 static void parse_declaration_rest(entity_t *ndeclaration,
5395 const declaration_specifiers_t *specifiers,
5396 parsed_declaration_func finished_declaration,
5397 declarator_flags_t flags)
5399 add_anchor_token(';');
5400 add_anchor_token(',');
5402 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5404 if (token.type == '=') {
5405 parse_init_declarator_rest(entity);
5406 } else if (entity->kind == ENTITY_VARIABLE) {
5407 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5408 * [...] where the extern specifier is explicitly used. */
5409 declaration_t *decl = &entity->declaration;
5410 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5411 type_t *type = decl->type;
5412 if (is_type_reference(skip_typeref(type))) {
5413 errorf(&entity->base.source_position,
5414 "reference '%#T' must be initialized",
5415 type, entity->base.symbol);
5420 check_variable_type_complete(entity);
5422 if (token.type != ',')
5426 add_anchor_token('=');
5427 ndeclaration = parse_declarator(specifiers, flags);
5428 rem_anchor_token('=');
5430 expect(';', end_error);
5433 anonymous_entity = NULL;
5434 rem_anchor_token(';');
5435 rem_anchor_token(',');
5438 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5440 symbol_t *symbol = entity->base.symbol;
5441 if (symbol == NULL) {
5442 errorf(HERE, "anonymous declaration not valid as function parameter");
5446 assert(entity->base.namespc == NAMESPACE_NORMAL);
5447 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5448 if (previous_entity == NULL
5449 || previous_entity->base.parent_scope != current_scope) {
5450 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5455 if (is_definition) {
5456 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5459 return record_entity(entity, false);
5462 static void parse_declaration(parsed_declaration_func finished_declaration,
5463 declarator_flags_t flags)
5465 declaration_specifiers_t specifiers;
5466 memset(&specifiers, 0, sizeof(specifiers));
5468 add_anchor_token(';');
5469 parse_declaration_specifiers(&specifiers);
5470 rem_anchor_token(';');
5472 if (token.type == ';') {
5473 parse_anonymous_declaration_rest(&specifiers);
5475 entity_t *entity = parse_declarator(&specifiers, flags);
5476 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5480 static type_t *get_default_promoted_type(type_t *orig_type)
5482 type_t *result = orig_type;
5484 type_t *type = skip_typeref(orig_type);
5485 if (is_type_integer(type)) {
5486 result = promote_integer(type);
5487 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
5488 result = type_double;
5494 static void parse_kr_declaration_list(entity_t *entity)
5496 if (entity->kind != ENTITY_FUNCTION)
5499 type_t *type = skip_typeref(entity->declaration.type);
5500 assert(is_type_function(type));
5501 if (!type->function.kr_style_parameters)
5505 add_anchor_token('{');
5507 /* push function parameters */
5508 size_t const top = environment_top();
5509 scope_t *old_scope = scope_push(&entity->function.parameters);
5511 entity_t *parameter = entity->function.parameters.entities;
5512 for ( ; parameter != NULL; parameter = parameter->base.next) {
5513 assert(parameter->base.parent_scope == NULL);
5514 parameter->base.parent_scope = current_scope;
5515 environment_push(parameter);
5518 /* parse declaration list */
5520 switch (token.type) {
5522 case T___extension__:
5523 /* This covers symbols, which are no type, too, and results in
5524 * better error messages. The typical cases are misspelled type
5525 * names and missing includes. */
5527 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5535 /* pop function parameters */
5536 assert(current_scope == &entity->function.parameters);
5537 scope_pop(old_scope);
5538 environment_pop_to(top);
5540 /* update function type */
5541 type_t *new_type = duplicate_type(type);
5543 function_parameter_t *parameters = NULL;
5544 function_parameter_t *last_parameter = NULL;
5546 parameter = entity->function.parameters.entities;
5547 for (; parameter != NULL; parameter = parameter->base.next) {
5548 if (parameter->kind != ENTITY_PARAMETER)
5551 type_t *parameter_type = parameter->declaration.type;
5552 if (parameter_type == NULL) {
5554 errorf(HERE, "no type specified for function parameter '%Y'",
5555 parameter->base.symbol);
5557 if (warning.implicit_int) {
5558 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5559 parameter->base.symbol);
5561 parameter_type = type_int;
5562 parameter->declaration.type = parameter_type;
5566 semantic_parameter_incomplete(parameter);
5567 parameter_type = parameter->declaration.type;
5570 * we need the default promoted types for the function type
5572 parameter_type = get_default_promoted_type(parameter_type);
5574 function_parameter_t *function_parameter
5575 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5576 memset(function_parameter, 0, sizeof(function_parameter[0]));
5578 function_parameter->type = parameter_type;
5579 if (last_parameter != NULL) {
5580 last_parameter->next = function_parameter;
5582 parameters = function_parameter;
5584 last_parameter = function_parameter;
5587 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
5589 new_type->function.parameters = parameters;
5590 new_type->function.unspecified_parameters = true;
5592 new_type = identify_new_type(new_type);
5594 entity->declaration.type = new_type;
5596 rem_anchor_token('{');
5599 static bool first_err = true;
5602 * When called with first_err set, prints the name of the current function,
5605 static void print_in_function(void)
5609 diagnosticf("%s: In function '%Y':\n",
5610 current_function->base.base.source_position.input_name,
5611 current_function->base.base.symbol);
5616 * Check if all labels are defined in the current function.
5617 * Check if all labels are used in the current function.
5619 static void check_labels(void)
5621 for (const goto_statement_t *goto_statement = goto_first;
5622 goto_statement != NULL;
5623 goto_statement = goto_statement->next) {
5624 /* skip computed gotos */
5625 if (goto_statement->expression != NULL)
5628 label_t *label = goto_statement->label;
5631 if (label->base.source_position.input_name == NULL) {
5632 print_in_function();
5633 errorf(&goto_statement->base.source_position,
5634 "label '%Y' used but not defined", label->base.symbol);
5638 if (warning.unused_label) {
5639 for (const label_statement_t *label_statement = label_first;
5640 label_statement != NULL;
5641 label_statement = label_statement->next) {
5642 label_t *label = label_statement->label;
5644 if (! label->used) {
5645 print_in_function();
5646 warningf(&label_statement->base.source_position,
5647 "label '%Y' defined but not used", label->base.symbol);
5653 static void warn_unused_entity(entity_t *entity, entity_t *last)
5655 entity_t const *const end = last != NULL ? last->base.next : NULL;
5656 for (; entity != end; entity = entity->base.next) {
5657 if (!is_declaration(entity))
5660 declaration_t *declaration = &entity->declaration;
5661 if (declaration->implicit)
5664 if (!declaration->used) {
5665 print_in_function();
5666 const char *what = get_entity_kind_name(entity->kind);
5667 warningf(&entity->base.source_position, "%s '%Y' is unused",
5668 what, entity->base.symbol);
5669 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5670 print_in_function();
5671 const char *what = get_entity_kind_name(entity->kind);
5672 warningf(&entity->base.source_position, "%s '%Y' is never read",
5673 what, entity->base.symbol);
5678 static void check_unused_variables(statement_t *const stmt, void *const env)
5682 switch (stmt->kind) {
5683 case STATEMENT_DECLARATION: {
5684 declaration_statement_t const *const decls = &stmt->declaration;
5685 warn_unused_entity(decls->declarations_begin,
5686 decls->declarations_end);
5691 warn_unused_entity(stmt->fors.scope.entities, NULL);
5700 * Check declarations of current_function for unused entities.
5702 static void check_declarations(void)
5704 if (warning.unused_parameter) {
5705 const scope_t *scope = ¤t_function->parameters;
5707 /* do not issue unused warnings for main */
5708 if (!is_sym_main(current_function->base.base.symbol)) {
5709 warn_unused_entity(scope->entities, NULL);
5712 if (warning.unused_variable) {
5713 walk_statements(current_function->statement, check_unused_variables,
5718 static int determine_truth(expression_t const* const cond)
5721 !is_constant_expression(cond) ? 0 :
5722 fold_constant(cond) != 0 ? 1 :
5726 static void check_reachable(statement_t *);
5727 static bool reaches_end;
5729 static bool expression_returns(expression_t const *const expr)
5731 switch (expr->kind) {
5733 expression_t const *const func = expr->call.function;
5734 if (func->kind == EXPR_REFERENCE) {
5735 entity_t *entity = func->reference.entity;
5736 if (entity->kind == ENTITY_FUNCTION
5737 && entity->declaration.modifiers & DM_NORETURN)
5741 if (!expression_returns(func))
5744 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5745 if (!expression_returns(arg->expression))
5752 case EXPR_REFERENCE:
5753 case EXPR_REFERENCE_ENUM_VALUE:
5755 case EXPR_CHARACTER_CONSTANT:
5756 case EXPR_WIDE_CHARACTER_CONSTANT:
5757 case EXPR_STRING_LITERAL:
5758 case EXPR_WIDE_STRING_LITERAL:
5759 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5760 case EXPR_LABEL_ADDRESS:
5761 case EXPR_CLASSIFY_TYPE:
5762 case EXPR_SIZEOF: // TODO handle obscure VLA case
5765 case EXPR_BUILTIN_SYMBOL:
5766 case EXPR_BUILTIN_CONSTANT_P:
5767 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5772 case EXPR_STATEMENT: {
5773 bool old_reaches_end = reaches_end;
5774 reaches_end = false;
5775 check_reachable(expr->statement.statement);
5776 bool returns = reaches_end;
5777 reaches_end = old_reaches_end;
5781 case EXPR_CONDITIONAL:
5782 // TODO handle constant expression
5784 if (!expression_returns(expr->conditional.condition))
5787 if (expr->conditional.true_expression != NULL
5788 && expression_returns(expr->conditional.true_expression))
5791 return expression_returns(expr->conditional.false_expression);
5794 return expression_returns(expr->select.compound);
5796 case EXPR_ARRAY_ACCESS:
5798 expression_returns(expr->array_access.array_ref) &&
5799 expression_returns(expr->array_access.index);
5802 return expression_returns(expr->va_starte.ap);
5805 return expression_returns(expr->va_arge.ap);
5807 EXPR_UNARY_CASES_MANDATORY
5808 return expression_returns(expr->unary.value);
5810 case EXPR_UNARY_THROW:
5814 // TODO handle constant lhs of && and ||
5816 expression_returns(expr->binary.left) &&
5817 expression_returns(expr->binary.right);
5823 panic("unhandled expression");
5826 static bool initializer_returns(initializer_t const *const init)
5828 switch (init->kind) {
5829 case INITIALIZER_VALUE:
5830 return expression_returns(init->value.value);
5832 case INITIALIZER_LIST: {
5833 initializer_t * const* i = init->list.initializers;
5834 initializer_t * const* const end = i + init->list.len;
5835 bool returns = true;
5836 for (; i != end; ++i) {
5837 if (!initializer_returns(*i))
5843 case INITIALIZER_STRING:
5844 case INITIALIZER_WIDE_STRING:
5845 case INITIALIZER_DESIGNATOR: // designators have no payload
5848 panic("unhandled initializer");
5851 static bool noreturn_candidate;
5853 static void check_reachable(statement_t *const stmt)
5855 if (stmt->base.reachable)
5857 if (stmt->kind != STATEMENT_DO_WHILE)
5858 stmt->base.reachable = true;
5860 statement_t *last = stmt;
5862 switch (stmt->kind) {
5863 case STATEMENT_INVALID:
5864 case STATEMENT_EMPTY:
5866 next = stmt->base.next;
5869 case STATEMENT_DECLARATION: {
5870 declaration_statement_t const *const decl = &stmt->declaration;
5871 entity_t const * ent = decl->declarations_begin;
5872 entity_t const *const last = decl->declarations_end;
5874 for (;; ent = ent->base.next) {
5875 if (ent->kind == ENTITY_VARIABLE &&
5876 ent->variable.initializer != NULL &&
5877 !initializer_returns(ent->variable.initializer)) {
5884 next = stmt->base.next;
5888 case STATEMENT_COMPOUND:
5889 next = stmt->compound.statements;
5891 next = stmt->base.next;
5894 case STATEMENT_RETURN: {
5895 expression_t const *const val = stmt->returns.value;
5896 if (val == NULL || expression_returns(val))
5897 noreturn_candidate = false;
5901 case STATEMENT_IF: {
5902 if_statement_t const *const ifs = &stmt->ifs;
5903 expression_t const *const cond = ifs->condition;
5905 if (!expression_returns(cond))
5908 int const val = determine_truth(cond);
5911 check_reachable(ifs->true_statement);
5916 if (ifs->false_statement != NULL) {
5917 check_reachable(ifs->false_statement);
5921 next = stmt->base.next;
5925 case STATEMENT_SWITCH: {
5926 switch_statement_t const *const switchs = &stmt->switchs;
5927 expression_t const *const expr = switchs->expression;
5929 if (!expression_returns(expr))
5932 if (is_constant_expression(expr)) {
5933 long const val = fold_constant(expr);
5934 case_label_statement_t * defaults = NULL;
5935 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5936 if (i->expression == NULL) {
5941 if (i->first_case <= val && val <= i->last_case) {
5942 check_reachable((statement_t*)i);
5947 if (defaults != NULL) {
5948 check_reachable((statement_t*)defaults);
5952 bool has_default = false;
5953 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5954 if (i->expression == NULL)
5957 check_reachable((statement_t*)i);
5964 next = stmt->base.next;
5968 case STATEMENT_EXPRESSION: {
5969 /* Check for noreturn function call */
5970 expression_t const *const expr = stmt->expression.expression;
5971 if (!expression_returns(expr))
5974 next = stmt->base.next;
5978 case STATEMENT_CONTINUE: {
5979 statement_t *parent = stmt;
5981 parent = parent->base.parent;
5982 if (parent == NULL) /* continue not within loop */
5986 switch (parent->kind) {
5987 case STATEMENT_WHILE: goto continue_while;
5988 case STATEMENT_DO_WHILE: goto continue_do_while;
5989 case STATEMENT_FOR: goto continue_for;
5996 case STATEMENT_BREAK: {
5997 statement_t *parent = stmt;
5999 parent = parent->base.parent;
6000 if (parent == NULL) /* break not within loop/switch */
6003 switch (parent->kind) {
6004 case STATEMENT_SWITCH:
6005 case STATEMENT_WHILE:
6006 case STATEMENT_DO_WHILE:
6009 next = parent->base.next;
6010 goto found_break_parent;
6019 case STATEMENT_GOTO:
6020 if (stmt->gotos.expression) {
6021 if (!expression_returns(stmt->gotos.expression))
6024 statement_t *parent = stmt->base.parent;
6025 if (parent == NULL) /* top level goto */
6029 next = stmt->gotos.label->statement;
6030 if (next == NULL) /* missing label */
6035 case STATEMENT_LABEL:
6036 next = stmt->label.statement;
6039 case STATEMENT_CASE_LABEL:
6040 next = stmt->case_label.statement;
6043 case STATEMENT_WHILE: {
6044 while_statement_t const *const whiles = &stmt->whiles;
6045 expression_t const *const cond = whiles->condition;
6047 if (!expression_returns(cond))
6050 int const val = determine_truth(cond);
6053 check_reachable(whiles->body);
6058 next = stmt->base.next;
6062 case STATEMENT_DO_WHILE:
6063 next = stmt->do_while.body;
6066 case STATEMENT_FOR: {
6067 for_statement_t *const fors = &stmt->fors;
6069 if (fors->condition_reachable)
6071 fors->condition_reachable = true;
6073 expression_t const *const cond = fors->condition;
6078 } else if (expression_returns(cond)) {
6079 val = determine_truth(cond);
6085 check_reachable(fors->body);
6090 next = stmt->base.next;
6094 case STATEMENT_MS_TRY: {
6095 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6096 check_reachable(ms_try->try_statement);
6097 next = ms_try->final_statement;
6101 case STATEMENT_LEAVE: {
6102 statement_t *parent = stmt;
6104 parent = parent->base.parent;
6105 if (parent == NULL) /* __leave not within __try */
6108 if (parent->kind == STATEMENT_MS_TRY) {
6110 next = parent->ms_try.final_statement;
6118 panic("invalid statement kind");
6121 while (next == NULL) {
6122 next = last->base.parent;
6124 noreturn_candidate = false;
6126 type_t *const type = skip_typeref(current_function->base.type);
6127 assert(is_type_function(type));
6128 type_t *const ret = skip_typeref(type->function.return_type);
6129 if (warning.return_type &&
6130 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6131 is_type_valid(ret) &&
6132 !is_sym_main(current_function->base.base.symbol)) {
6133 warningf(&stmt->base.source_position,
6134 "control reaches end of non-void function");
6139 switch (next->kind) {
6140 case STATEMENT_INVALID:
6141 case STATEMENT_EMPTY:
6142 case STATEMENT_DECLARATION:
6143 case STATEMENT_EXPRESSION:
6145 case STATEMENT_RETURN:
6146 case STATEMENT_CONTINUE:
6147 case STATEMENT_BREAK:
6148 case STATEMENT_GOTO:
6149 case STATEMENT_LEAVE:
6150 panic("invalid control flow in function");
6152 case STATEMENT_COMPOUND:
6153 if (next->compound.stmt_expr) {
6159 case STATEMENT_SWITCH:
6160 case STATEMENT_LABEL:
6161 case STATEMENT_CASE_LABEL:
6163 next = next->base.next;
6166 case STATEMENT_WHILE: {
6168 if (next->base.reachable)
6170 next->base.reachable = true;
6172 while_statement_t const *const whiles = &next->whiles;
6173 expression_t const *const cond = whiles->condition;
6175 if (!expression_returns(cond))
6178 int const val = determine_truth(cond);
6181 check_reachable(whiles->body);
6187 next = next->base.next;
6191 case STATEMENT_DO_WHILE: {
6193 if (next->base.reachable)
6195 next->base.reachable = true;
6197 do_while_statement_t const *const dw = &next->do_while;
6198 expression_t const *const cond = dw->condition;
6200 if (!expression_returns(cond))
6203 int const val = determine_truth(cond);
6206 check_reachable(dw->body);
6212 next = next->base.next;
6216 case STATEMENT_FOR: {
6218 for_statement_t *const fors = &next->fors;
6220 fors->step_reachable = true;
6222 if (fors->condition_reachable)
6224 fors->condition_reachable = true;
6226 expression_t const *const cond = fors->condition;
6231 } else if (expression_returns(cond)) {
6232 val = determine_truth(cond);
6238 check_reachable(fors->body);
6244 next = next->base.next;
6248 case STATEMENT_MS_TRY:
6250 next = next->ms_try.final_statement;
6255 check_reachable(next);
6258 static void check_unreachable(statement_t* const stmt, void *const env)
6262 switch (stmt->kind) {
6263 case STATEMENT_DO_WHILE:
6264 if (!stmt->base.reachable) {
6265 expression_t const *const cond = stmt->do_while.condition;
6266 if (determine_truth(cond) >= 0) {
6267 warningf(&cond->base.source_position,
6268 "condition of do-while-loop is unreachable");
6273 case STATEMENT_FOR: {
6274 for_statement_t const* const fors = &stmt->fors;
6276 // if init and step are unreachable, cond is unreachable, too
6277 if (!stmt->base.reachable && !fors->step_reachable) {
6278 warningf(&stmt->base.source_position, "statement is unreachable");
6280 if (!stmt->base.reachable && fors->initialisation != NULL) {
6281 warningf(&fors->initialisation->base.source_position,
6282 "initialisation of for-statement is unreachable");
6285 if (!fors->condition_reachable && fors->condition != NULL) {
6286 warningf(&fors->condition->base.source_position,
6287 "condition of for-statement is unreachable");
6290 if (!fors->step_reachable && fors->step != NULL) {
6291 warningf(&fors->step->base.source_position,
6292 "step of for-statement is unreachable");
6298 case STATEMENT_COMPOUND:
6299 if (stmt->compound.statements != NULL)
6301 goto warn_unreachable;
6303 case STATEMENT_DECLARATION: {
6304 /* Only warn if there is at least one declarator with an initializer.
6305 * This typically occurs in switch statements. */
6306 declaration_statement_t const *const decl = &stmt->declaration;
6307 entity_t const * ent = decl->declarations_begin;
6308 entity_t const *const last = decl->declarations_end;
6310 for (;; ent = ent->base.next) {
6311 if (ent->kind == ENTITY_VARIABLE &&
6312 ent->variable.initializer != NULL) {
6313 goto warn_unreachable;
6323 if (!stmt->base.reachable)
6324 warningf(&stmt->base.source_position, "statement is unreachable");
6329 static void parse_external_declaration(void)
6331 /* function-definitions and declarations both start with declaration
6333 declaration_specifiers_t specifiers;
6334 memset(&specifiers, 0, sizeof(specifiers));
6336 add_anchor_token(';');
6337 parse_declaration_specifiers(&specifiers);
6338 rem_anchor_token(';');
6340 /* must be a declaration */
6341 if (token.type == ';') {
6342 parse_anonymous_declaration_rest(&specifiers);
6346 add_anchor_token(',');
6347 add_anchor_token('=');
6348 add_anchor_token(';');
6349 add_anchor_token('{');
6351 /* declarator is common to both function-definitions and declarations */
6352 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6354 rem_anchor_token('{');
6355 rem_anchor_token(';');
6356 rem_anchor_token('=');
6357 rem_anchor_token(',');
6359 /* must be a declaration */
6360 switch (token.type) {
6364 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6369 /* must be a function definition */
6370 parse_kr_declaration_list(ndeclaration);
6372 if (token.type != '{') {
6373 parse_error_expected("while parsing function definition", '{', NULL);
6374 eat_until_matching_token(';');
6378 assert(is_declaration(ndeclaration));
6379 type_t *const orig_type = ndeclaration->declaration.type;
6380 type_t * type = skip_typeref(orig_type);
6382 if (!is_type_function(type)) {
6383 if (is_type_valid(type)) {
6384 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6385 type, ndeclaration->base.symbol);
6389 } else if (is_typeref(orig_type)) {
6391 errorf(&ndeclaration->base.source_position,
6392 "type of function definition '%#T' is a typedef",
6393 orig_type, ndeclaration->base.symbol);
6396 if (warning.aggregate_return &&
6397 is_type_compound(skip_typeref(type->function.return_type))) {
6398 warningf(HERE, "function '%Y' returns an aggregate",
6399 ndeclaration->base.symbol);
6401 if (warning.traditional && !type->function.unspecified_parameters) {
6402 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6403 ndeclaration->base.symbol);
6405 if (warning.old_style_definition && type->function.unspecified_parameters) {
6406 warningf(HERE, "old-style function definition '%Y'",
6407 ndeclaration->base.symbol);
6410 /* §6.7.5.3:14 a function definition with () means no
6411 * parameters (and not unspecified parameters) */
6412 if (type->function.unspecified_parameters &&
6413 type->function.parameters == NULL &&
6414 !type->function.kr_style_parameters) {
6415 type_t *copy = duplicate_type(type);
6416 copy->function.unspecified_parameters = false;
6417 type = identify_new_type(copy);
6419 ndeclaration->declaration.type = type;
6422 entity_t *const entity = record_entity(ndeclaration, true);
6423 assert(entity->kind == ENTITY_FUNCTION);
6424 assert(ndeclaration->kind == ENTITY_FUNCTION);
6426 function_t *function = &entity->function;
6427 if (ndeclaration != entity) {
6428 function->parameters = ndeclaration->function.parameters;
6430 assert(is_declaration(entity));
6431 type = skip_typeref(entity->declaration.type);
6433 /* push function parameters and switch scope */
6434 size_t const top = environment_top();
6435 scope_t *old_scope = scope_push(&function->parameters);
6437 entity_t *parameter = function->parameters.entities;
6438 for (; parameter != NULL; parameter = parameter->base.next) {
6439 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6440 parameter->base.parent_scope = current_scope;
6442 assert(parameter->base.parent_scope == NULL
6443 || parameter->base.parent_scope == current_scope);
6444 parameter->base.parent_scope = current_scope;
6445 if (parameter->base.symbol == NULL) {
6446 errorf(¶meter->base.source_position, "parameter name omitted");
6449 environment_push(parameter);
6452 if (function->statement != NULL) {
6453 parser_error_multiple_definition(entity, HERE);
6456 /* parse function body */
6457 int label_stack_top = label_top();
6458 function_t *old_current_function = current_function;
6459 current_function = function;
6460 current_parent = NULL;
6463 goto_anchor = &goto_first;
6465 label_anchor = &label_first;
6467 statement_t *const body = parse_compound_statement(false);
6468 function->statement = body;
6471 check_declarations();
6472 if (warning.return_type ||
6473 warning.unreachable_code ||
6474 (warning.missing_noreturn
6475 && !(function->base.modifiers & DM_NORETURN))) {
6476 noreturn_candidate = true;
6477 check_reachable(body);
6478 if (warning.unreachable_code)
6479 walk_statements(body, check_unreachable, NULL);
6480 if (warning.missing_noreturn &&
6481 noreturn_candidate &&
6482 !(function->base.modifiers & DM_NORETURN)) {
6483 warningf(&body->base.source_position,
6484 "function '%#T' is candidate for attribute 'noreturn'",
6485 type, entity->base.symbol);
6489 assert(current_parent == NULL);
6490 assert(current_function == function);
6491 current_function = old_current_function;
6492 label_pop_to(label_stack_top);
6495 assert(current_scope == &function->parameters);
6496 scope_pop(old_scope);
6497 environment_pop_to(top);
6500 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6501 source_position_t *source_position,
6502 const symbol_t *symbol)
6504 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6506 type->bitfield.base_type = base_type;
6507 type->bitfield.size_expression = size;
6510 type_t *skipped_type = skip_typeref(base_type);
6511 if (!is_type_integer(skipped_type)) {
6512 errorf(HERE, "bitfield base type '%T' is not an integer type",
6516 bit_size = skipped_type->base.size * 8;
6519 if (is_constant_expression(size)) {
6520 long v = fold_constant(size);
6523 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6524 } else if (v == 0) {
6525 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6526 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6527 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6529 type->bitfield.bit_size = v;
6536 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6538 entity_t *iter = compound->members.entities;
6539 for (; iter != NULL; iter = iter->base.next) {
6540 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6543 if (iter->base.symbol == symbol) {
6545 } else if (iter->base.symbol == NULL) {
6546 type_t *type = skip_typeref(iter->declaration.type);
6547 if (is_type_compound(type)) {
6549 = find_compound_entry(type->compound.compound, symbol);
6560 static void parse_compound_declarators(compound_t *compound,
6561 const declaration_specifiers_t *specifiers)
6566 if (token.type == ':') {
6567 source_position_t source_position = *HERE;
6570 type_t *base_type = specifiers->type;
6571 expression_t *size = parse_constant_expression();
6573 type_t *type = make_bitfield_type(base_type, size,
6574 &source_position, sym_anonymous);
6576 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6577 entity->base.namespc = NAMESPACE_NORMAL;
6578 entity->base.source_position = source_position;
6579 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6580 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6581 entity->declaration.modifiers = specifiers->modifiers;
6582 entity->declaration.type = type;
6583 append_entity(&compound->members, entity);
6585 entity = parse_declarator(specifiers,
6586 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6587 if (entity->kind == ENTITY_TYPEDEF) {
6588 errorf(&entity->base.source_position,
6589 "typedef not allowed as compound member");
6591 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6593 /* make sure we don't define a symbol multiple times */
6594 symbol_t *symbol = entity->base.symbol;
6595 if (symbol != NULL) {
6596 entity_t *prev = find_compound_entry(compound, symbol);
6598 errorf(&entity->base.source_position,
6599 "multiple declarations of symbol '%Y' (declared %P)",
6600 symbol, &prev->base.source_position);
6604 if (token.type == ':') {
6605 source_position_t source_position = *HERE;
6607 expression_t *size = parse_constant_expression();
6609 type_t *type = entity->declaration.type;
6610 type_t *bitfield_type = make_bitfield_type(type, size,
6611 &source_position, entity->base.symbol);
6612 entity->declaration.type = bitfield_type;
6614 type_t *orig_type = entity->declaration.type;
6615 type_t *type = skip_typeref(orig_type);
6616 if (is_type_function(type)) {
6617 errorf(&entity->base.source_position,
6618 "compound member '%Y' must not have function type '%T'",
6619 entity->base.symbol, orig_type);
6620 } else if (is_type_incomplete(type)) {
6621 /* §6.7.2.1:16 flexible array member */
6622 if (is_type_array(type) &&
6623 token.type == ';' &&
6624 look_ahead(1)->type == '}') {
6625 compound->has_flexible_member = true;
6627 errorf(&entity->base.source_position,
6628 "compound member '%Y' has incomplete type '%T'",
6629 entity->base.symbol, orig_type);
6634 append_entity(&compound->members, entity);
6638 if (token.type != ',')
6642 expect(';', end_error);
6645 anonymous_entity = NULL;
6648 static void parse_compound_type_entries(compound_t *compound)
6651 add_anchor_token('}');
6653 while (token.type != '}') {
6654 if (token.type == T_EOF) {
6655 errorf(HERE, "EOF while parsing struct");
6658 declaration_specifiers_t specifiers;
6659 memset(&specifiers, 0, sizeof(specifiers));
6660 parse_declaration_specifiers(&specifiers);
6662 parse_compound_declarators(compound, &specifiers);
6664 rem_anchor_token('}');
6668 compound->complete = true;
6671 static type_t *parse_typename(void)
6673 declaration_specifiers_t specifiers;
6674 memset(&specifiers, 0, sizeof(specifiers));
6675 parse_declaration_specifiers(&specifiers);
6676 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6677 specifiers.thread_local) {
6678 /* TODO: improve error message, user does probably not know what a
6679 * storage class is...
6681 errorf(HERE, "typename may not have a storage class");
6684 type_t *result = parse_abstract_declarator(specifiers.type);
6692 typedef expression_t* (*parse_expression_function)(void);
6693 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6695 typedef struct expression_parser_function_t expression_parser_function_t;
6696 struct expression_parser_function_t {
6697 parse_expression_function parser;
6698 precedence_t infix_precedence;
6699 parse_expression_infix_function infix_parser;
6702 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6705 * Prints an error message if an expression was expected but not read
6707 static expression_t *expected_expression_error(void)
6709 /* skip the error message if the error token was read */
6710 if (token.type != T_ERROR) {
6711 errorf(HERE, "expected expression, got token %K", &token);
6715 return create_invalid_expression();
6719 * Parse a string constant.
6721 static expression_t *parse_string_const(void)
6724 if (token.type == T_STRING_LITERAL) {
6725 string_t res = token.v.string;
6727 while (token.type == T_STRING_LITERAL) {
6728 res = concat_strings(&res, &token.v.string);
6731 if (token.type != T_WIDE_STRING_LITERAL) {
6732 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6733 /* note: that we use type_char_ptr here, which is already the
6734 * automatic converted type. revert_automatic_type_conversion
6735 * will construct the array type */
6736 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6737 cnst->string.value = res;
6741 wres = concat_string_wide_string(&res, &token.v.wide_string);
6743 wres = token.v.wide_string;
6748 switch (token.type) {
6749 case T_WIDE_STRING_LITERAL:
6750 wres = concat_wide_strings(&wres, &token.v.wide_string);
6753 case T_STRING_LITERAL:
6754 wres = concat_wide_string_string(&wres, &token.v.string);
6758 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6759 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6760 cnst->wide_string.value = wres;
6769 * Parse a boolean constant.
6771 static expression_t *parse_bool_const(bool value)
6773 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6774 cnst->base.type = type_bool;
6775 cnst->conste.v.int_value = value;
6783 * Parse an integer constant.
6785 static expression_t *parse_int_const(void)
6787 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6788 cnst->base.type = token.datatype;
6789 cnst->conste.v.int_value = token.v.intvalue;
6797 * Parse a character constant.
6799 static expression_t *parse_character_constant(void)
6801 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6802 cnst->base.type = token.datatype;
6803 cnst->conste.v.character = token.v.string;
6805 if (cnst->conste.v.character.size != 1) {
6807 errorf(HERE, "more than 1 character in character constant");
6808 } else if (warning.multichar) {
6809 warningf(HERE, "multi-character character constant");
6818 * Parse a wide character constant.
6820 static expression_t *parse_wide_character_constant(void)
6822 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6823 cnst->base.type = token.datatype;
6824 cnst->conste.v.wide_character = token.v.wide_string;
6826 if (cnst->conste.v.wide_character.size != 1) {
6828 errorf(HERE, "more than 1 character in character constant");
6829 } else if (warning.multichar) {
6830 warningf(HERE, "multi-character character constant");
6839 * Parse a float constant.
6841 static expression_t *parse_float_const(void)
6843 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6844 cnst->base.type = token.datatype;
6845 cnst->conste.v.float_value = token.v.floatvalue;
6852 static entity_t *create_implicit_function(symbol_t *symbol,
6853 const source_position_t *source_position)
6855 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6856 ntype->function.return_type = type_int;
6857 ntype->function.unspecified_parameters = true;
6858 ntype->function.linkage = LINKAGE_C;
6859 type_t *type = identify_new_type(ntype);
6861 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6862 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6863 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6864 entity->declaration.type = type;
6865 entity->declaration.implicit = true;
6866 entity->base.symbol = symbol;
6867 entity->base.source_position = *source_position;
6869 bool strict_prototypes_old = warning.strict_prototypes;
6870 warning.strict_prototypes = false;
6871 record_entity(entity, false);
6872 warning.strict_prototypes = strict_prototypes_old;
6878 * Creates a return_type (func)(argument_type) function type if not
6881 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6882 type_t *argument_type2)
6884 function_parameter_t *parameter2
6885 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6886 memset(parameter2, 0, sizeof(parameter2[0]));
6887 parameter2->type = argument_type2;
6889 function_parameter_t *parameter1
6890 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6891 memset(parameter1, 0, sizeof(parameter1[0]));
6892 parameter1->type = argument_type1;
6893 parameter1->next = parameter2;
6895 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6896 type->function.return_type = return_type;
6897 type->function.parameters = parameter1;
6899 return identify_new_type(type);
6903 * Creates a return_type (func)(argument_type) function type if not
6906 * @param return_type the return type
6907 * @param argument_type the argument type
6909 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6911 function_parameter_t *parameter
6912 = obstack_alloc(type_obst, sizeof(parameter[0]));
6913 memset(parameter, 0, sizeof(parameter[0]));
6914 parameter->type = argument_type;
6916 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6917 type->function.return_type = return_type;
6918 type->function.parameters = parameter;
6920 return identify_new_type(type);
6923 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6925 type_t *res = make_function_1_type(return_type, argument_type);
6926 res->function.variadic = 1;
6931 * Creates a return_type (func)(void) function type if not
6934 * @param return_type the return type
6936 static type_t *make_function_0_type(type_t *return_type)
6938 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6939 type->function.return_type = return_type;
6940 type->function.parameters = NULL;
6942 return identify_new_type(type);
6946 * Creates a function type for some function like builtins.
6948 * @param symbol the symbol describing the builtin
6950 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6952 switch (symbol->ID) {
6953 case T___builtin_alloca:
6954 return make_function_1_type(type_void_ptr, type_size_t);
6955 case T___builtin_huge_val:
6956 return make_function_0_type(type_double);
6957 case T___builtin_inf:
6958 return make_function_0_type(type_double);
6959 case T___builtin_inff:
6960 return make_function_0_type(type_float);
6961 case T___builtin_infl:
6962 return make_function_0_type(type_long_double);
6963 case T___builtin_nan:
6964 return make_function_1_type(type_double, type_char_ptr);
6965 case T___builtin_nanf:
6966 return make_function_1_type(type_float, type_char_ptr);
6967 case T___builtin_nanl:
6968 return make_function_1_type(type_long_double, type_char_ptr);
6969 case T___builtin_va_end:
6970 return make_function_1_type(type_void, type_valist);
6971 case T___builtin_expect:
6972 return make_function_2_type(type_long, type_long, type_long);
6973 case T___builtin_return_address:
6974 case T___builtin_frame_address:
6975 return make_function_1_type(type_void_ptr, type_unsigned_int);
6976 case T___builtin_ffs:
6977 case T___builtin_clz:
6978 case T___builtin_ctz:
6979 case T___builtin_popcount:
6980 case T___builtin_parity:
6981 return make_function_1_type(type_int, type_unsigned_int);
6982 case T___builtin_prefetch:
6983 return make_function_1_type_variadic(type_float, type_void_ptr);
6984 case T___builtin_trap: {
6985 type_t *type = make_function_0_type(type_void);
6986 type->function.base.modifiers |= DM_NORETURN;
6990 internal_errorf(HERE, "not implemented builtin identifier found");
6995 * Performs automatic type cast as described in §6.3.2.1.
6997 * @param orig_type the original type
6999 static type_t *automatic_type_conversion(type_t *orig_type)
7001 type_t *type = skip_typeref(orig_type);
7002 if (is_type_array(type)) {
7003 array_type_t *array_type = &type->array;
7004 type_t *element_type = array_type->element_type;
7005 unsigned qualifiers = array_type->base.qualifiers;
7007 return make_pointer_type(element_type, qualifiers);
7010 if (is_type_function(type)) {
7011 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7018 * reverts the automatic casts of array to pointer types and function
7019 * to function-pointer types as defined §6.3.2.1
7021 type_t *revert_automatic_type_conversion(const expression_t *expression)
7023 switch (expression->kind) {
7024 case EXPR_REFERENCE: {
7025 entity_t *entity = expression->reference.entity;
7026 if (is_declaration(entity)) {
7027 return entity->declaration.type;
7028 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7029 return entity->enum_value.enum_type;
7031 panic("no declaration or enum in reference");
7036 entity_t *entity = expression->select.compound_entry;
7037 assert(is_declaration(entity));
7038 type_t *type = entity->declaration.type;
7039 return get_qualified_type(type,
7040 expression->base.type->base.qualifiers);
7043 case EXPR_UNARY_DEREFERENCE: {
7044 const expression_t *const value = expression->unary.value;
7045 type_t *const type = skip_typeref(value->base.type);
7046 if (!is_type_pointer(type))
7047 return type_error_type;
7048 return type->pointer.points_to;
7051 case EXPR_BUILTIN_SYMBOL:
7052 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
7054 case EXPR_ARRAY_ACCESS: {
7055 const expression_t *array_ref = expression->array_access.array_ref;
7056 type_t *type_left = skip_typeref(array_ref->base.type);
7057 if (!is_type_pointer(type_left))
7058 return type_error_type;
7059 return type_left->pointer.points_to;
7062 case EXPR_STRING_LITERAL: {
7063 size_t size = expression->string.value.size;
7064 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
7067 case EXPR_WIDE_STRING_LITERAL: {
7068 size_t size = expression->wide_string.value.size;
7069 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
7072 case EXPR_COMPOUND_LITERAL:
7073 return expression->compound_literal.type;
7076 return expression->base.type;
7080 static expression_t *parse_reference(void)
7082 symbol_t *const symbol = token.v.symbol;
7084 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
7086 if (entity == NULL) {
7087 if (!strict_mode && look_ahead(1)->type == '(') {
7088 /* an implicitly declared function */
7089 if (warning.error_implicit_function_declaration) {
7090 errorf(HERE, "implicit declaration of function '%Y'", symbol);
7091 } else if (warning.implicit_function_declaration) {
7092 warningf(HERE, "implicit declaration of function '%Y'", symbol);
7095 entity = create_implicit_function(symbol, HERE);
7097 errorf(HERE, "unknown identifier '%Y' found.", symbol);
7098 entity = create_error_entity(symbol, ENTITY_VARIABLE);
7104 if (is_declaration(entity)) {
7105 orig_type = entity->declaration.type;
7106 } else if (entity->kind == ENTITY_ENUM_VALUE) {
7107 orig_type = entity->enum_value.enum_type;
7108 } else if (entity->kind == ENTITY_TYPEDEF) {
7109 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
7112 return create_invalid_expression();
7114 panic("expected declaration or enum value in reference");
7117 /* we always do the auto-type conversions; the & and sizeof parser contains
7118 * code to revert this! */
7119 type_t *type = automatic_type_conversion(orig_type);
7121 expression_kind_t kind = EXPR_REFERENCE;
7122 if (entity->kind == ENTITY_ENUM_VALUE)
7123 kind = EXPR_REFERENCE_ENUM_VALUE;
7125 expression_t *expression = allocate_expression_zero(kind);
7126 expression->reference.entity = entity;
7127 expression->base.type = type;
7129 /* this declaration is used */
7130 if (is_declaration(entity)) {
7131 entity->declaration.used = true;
7134 if (entity->base.parent_scope != file_scope
7135 && entity->base.parent_scope->depth < current_function->parameters.depth
7136 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7137 if (entity->kind == ENTITY_VARIABLE) {
7138 /* access of a variable from an outer function */
7139 entity->variable.address_taken = true;
7140 } else if (entity->kind == ENTITY_PARAMETER) {
7141 entity->parameter.address_taken = true;
7143 current_function->need_closure = true;
7146 /* check for deprecated functions */
7147 if (warning.deprecated_declarations
7148 && is_declaration(entity)
7149 && entity->declaration.modifiers & DM_DEPRECATED) {
7150 declaration_t *declaration = &entity->declaration;
7152 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7153 "function" : "variable";
7155 if (declaration->deprecated_string != NULL) {
7156 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7157 prefix, entity->base.symbol, &entity->base.source_position,
7158 declaration->deprecated_string);
7160 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7161 entity->base.symbol, &entity->base.source_position);
7165 if (warning.init_self && entity == current_init_decl && !in_type_prop
7166 && entity->kind == ENTITY_VARIABLE) {
7167 current_init_decl = NULL;
7168 warningf(HERE, "variable '%#T' is initialized by itself",
7169 entity->declaration.type, entity->base.symbol);
7176 static bool semantic_cast(expression_t *cast)
7178 expression_t *expression = cast->unary.value;
7179 type_t *orig_dest_type = cast->base.type;
7180 type_t *orig_type_right = expression->base.type;
7181 type_t const *dst_type = skip_typeref(orig_dest_type);
7182 type_t const *src_type = skip_typeref(orig_type_right);
7183 source_position_t const *pos = &cast->base.source_position;
7185 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7186 if (dst_type == type_void)
7189 /* only integer and pointer can be casted to pointer */
7190 if (is_type_pointer(dst_type) &&
7191 !is_type_pointer(src_type) &&
7192 !is_type_integer(src_type) &&
7193 is_type_valid(src_type)) {
7194 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7198 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7199 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7203 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7204 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7208 if (warning.cast_qual &&
7209 is_type_pointer(src_type) &&
7210 is_type_pointer(dst_type)) {
7211 type_t *src = skip_typeref(src_type->pointer.points_to);
7212 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7213 unsigned missing_qualifiers =
7214 src->base.qualifiers & ~dst->base.qualifiers;
7215 if (missing_qualifiers != 0) {
7217 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7218 missing_qualifiers, orig_type_right);
7224 static expression_t *parse_compound_literal(type_t *type)
7226 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7228 parse_initializer_env_t env;
7231 env.must_be_constant = false;
7232 initializer_t *initializer = parse_initializer(&env);
7235 expression->compound_literal.initializer = initializer;
7236 expression->compound_literal.type = type;
7237 expression->base.type = automatic_type_conversion(type);
7243 * Parse a cast expression.
7245 static expression_t *parse_cast(void)
7247 add_anchor_token(')');
7249 source_position_t source_position = token.source_position;
7251 type_t *type = parse_typename();
7253 rem_anchor_token(')');
7254 expect(')', end_error);
7256 if (token.type == '{') {
7257 return parse_compound_literal(type);
7260 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7261 cast->base.source_position = source_position;
7263 expression_t *value = parse_sub_expression(PREC_CAST);
7264 cast->base.type = type;
7265 cast->unary.value = value;
7267 if (! semantic_cast(cast)) {
7268 /* TODO: record the error in the AST. else it is impossible to detect it */
7273 return create_invalid_expression();
7277 * Parse a statement expression.
7279 static expression_t *parse_statement_expression(void)
7281 add_anchor_token(')');
7283 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7285 statement_t *statement = parse_compound_statement(true);
7286 statement->compound.stmt_expr = true;
7287 expression->statement.statement = statement;
7289 /* find last statement and use its type */
7290 type_t *type = type_void;
7291 const statement_t *stmt = statement->compound.statements;
7293 while (stmt->base.next != NULL)
7294 stmt = stmt->base.next;
7296 if (stmt->kind == STATEMENT_EXPRESSION) {
7297 type = stmt->expression.expression->base.type;
7299 } else if (warning.other) {
7300 warningf(&expression->base.source_position, "empty statement expression ({})");
7302 expression->base.type = type;
7304 rem_anchor_token(')');
7305 expect(')', end_error);
7312 * Parse a parenthesized expression.
7314 static expression_t *parse_parenthesized_expression(void)
7318 switch (token.type) {
7320 /* gcc extension: a statement expression */
7321 return parse_statement_expression();
7325 return parse_cast();
7327 if (is_typedef_symbol(token.v.symbol)) {
7328 return parse_cast();
7332 add_anchor_token(')');
7333 expression_t *result = parse_expression();
7334 result->base.parenthesized = true;
7335 rem_anchor_token(')');
7336 expect(')', end_error);
7342 static expression_t *parse_function_keyword(void)
7346 if (current_function == NULL) {
7347 errorf(HERE, "'__func__' used outside of a function");
7350 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7351 expression->base.type = type_char_ptr;
7352 expression->funcname.kind = FUNCNAME_FUNCTION;
7359 static expression_t *parse_pretty_function_keyword(void)
7361 if (current_function == NULL) {
7362 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7365 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7366 expression->base.type = type_char_ptr;
7367 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7369 eat(T___PRETTY_FUNCTION__);
7374 static expression_t *parse_funcsig_keyword(void)
7376 if (current_function == NULL) {
7377 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7380 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7381 expression->base.type = type_char_ptr;
7382 expression->funcname.kind = FUNCNAME_FUNCSIG;
7389 static expression_t *parse_funcdname_keyword(void)
7391 if (current_function == NULL) {
7392 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7395 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7396 expression->base.type = type_char_ptr;
7397 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7399 eat(T___FUNCDNAME__);
7404 static designator_t *parse_designator(void)
7406 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7407 result->source_position = *HERE;
7409 if (token.type != T_IDENTIFIER) {
7410 parse_error_expected("while parsing member designator",
7411 T_IDENTIFIER, NULL);
7414 result->symbol = token.v.symbol;
7417 designator_t *last_designator = result;
7419 if (token.type == '.') {
7421 if (token.type != T_IDENTIFIER) {
7422 parse_error_expected("while parsing member designator",
7423 T_IDENTIFIER, NULL);
7426 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7427 designator->source_position = *HERE;
7428 designator->symbol = token.v.symbol;
7431 last_designator->next = designator;
7432 last_designator = designator;
7435 if (token.type == '[') {
7437 add_anchor_token(']');
7438 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7439 designator->source_position = *HERE;
7440 designator->array_index = parse_expression();
7441 rem_anchor_token(']');
7442 expect(']', end_error);
7443 if (designator->array_index == NULL) {
7447 last_designator->next = designator;
7448 last_designator = designator;
7460 * Parse the __builtin_offsetof() expression.
7462 static expression_t *parse_offsetof(void)
7464 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7465 expression->base.type = type_size_t;
7467 eat(T___builtin_offsetof);
7469 expect('(', end_error);
7470 add_anchor_token(',');
7471 type_t *type = parse_typename();
7472 rem_anchor_token(',');
7473 expect(',', end_error);
7474 add_anchor_token(')');
7475 designator_t *designator = parse_designator();
7476 rem_anchor_token(')');
7477 expect(')', end_error);
7479 expression->offsetofe.type = type;
7480 expression->offsetofe.designator = designator;
7483 memset(&path, 0, sizeof(path));
7484 path.top_type = type;
7485 path.path = NEW_ARR_F(type_path_entry_t, 0);
7487 descend_into_subtype(&path);
7489 if (!walk_designator(&path, designator, true)) {
7490 return create_invalid_expression();
7493 DEL_ARR_F(path.path);
7497 return create_invalid_expression();
7501 * Parses a _builtin_va_start() expression.
7503 static expression_t *parse_va_start(void)
7505 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7507 eat(T___builtin_va_start);
7509 expect('(', end_error);
7510 add_anchor_token(',');
7511 expression->va_starte.ap = parse_assignment_expression();
7512 rem_anchor_token(',');
7513 expect(',', end_error);
7514 expression_t *const expr = parse_assignment_expression();
7515 if (expr->kind == EXPR_REFERENCE) {
7516 entity_t *const entity = expr->reference.entity;
7517 if (entity->base.parent_scope != ¤t_function->parameters
7518 || entity->base.next != NULL
7519 || entity->kind != ENTITY_PARAMETER) {
7520 errorf(&expr->base.source_position,
7521 "second argument of 'va_start' must be last parameter of the current function");
7523 expression->va_starte.parameter = &entity->variable;
7525 expect(')', end_error);
7528 expect(')', end_error);
7530 return create_invalid_expression();
7534 * Parses a _builtin_va_arg() expression.
7536 static expression_t *parse_va_arg(void)
7538 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7540 eat(T___builtin_va_arg);
7542 expect('(', end_error);
7543 expression->va_arge.ap = parse_assignment_expression();
7544 expect(',', end_error);
7545 expression->base.type = parse_typename();
7546 expect(')', end_error);
7550 return create_invalid_expression();
7553 static expression_t *parse_builtin_symbol(void)
7555 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7557 symbol_t *symbol = token.v.symbol;
7559 expression->builtin_symbol.symbol = symbol;
7562 type_t *type = get_builtin_symbol_type(symbol);
7563 type = automatic_type_conversion(type);
7565 expression->base.type = type;
7570 * Parses a __builtin_constant_p() expression.
7572 static expression_t *parse_builtin_constant(void)
7574 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7576 eat(T___builtin_constant_p);
7578 expect('(', end_error);
7579 add_anchor_token(')');
7580 expression->builtin_constant.value = parse_assignment_expression();
7581 rem_anchor_token(')');
7582 expect(')', end_error);
7583 expression->base.type = type_int;
7587 return create_invalid_expression();
7591 * Parses a __builtin_types_compatible_p() expression.
7593 static expression_t *parse_builtin_types_compatible(void)
7595 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7597 eat(T___builtin_types_compatible_p);
7599 expect('(', end_error);
7600 add_anchor_token(')');
7601 add_anchor_token(',');
7602 expression->builtin_types_compatible.left = parse_typename();
7603 rem_anchor_token(',');
7604 expect(',', end_error);
7605 expression->builtin_types_compatible.right = parse_typename();
7606 rem_anchor_token(')');
7607 expect(')', end_error);
7608 expression->base.type = type_int;
7612 return create_invalid_expression();
7616 * Parses a __builtin_is_*() compare expression.
7618 static expression_t *parse_compare_builtin(void)
7620 expression_t *expression;
7622 switch (token.type) {
7623 case T___builtin_isgreater:
7624 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7626 case T___builtin_isgreaterequal:
7627 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7629 case T___builtin_isless:
7630 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7632 case T___builtin_islessequal:
7633 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7635 case T___builtin_islessgreater:
7636 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7638 case T___builtin_isunordered:
7639 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7642 internal_errorf(HERE, "invalid compare builtin found");
7644 expression->base.source_position = *HERE;
7647 expect('(', end_error);
7648 expression->binary.left = parse_assignment_expression();
7649 expect(',', end_error);
7650 expression->binary.right = parse_assignment_expression();
7651 expect(')', end_error);
7653 type_t *const orig_type_left = expression->binary.left->base.type;
7654 type_t *const orig_type_right = expression->binary.right->base.type;
7656 type_t *const type_left = skip_typeref(orig_type_left);
7657 type_t *const type_right = skip_typeref(orig_type_right);
7658 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7659 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7660 type_error_incompatible("invalid operands in comparison",
7661 &expression->base.source_position, orig_type_left, orig_type_right);
7664 semantic_comparison(&expression->binary);
7669 return create_invalid_expression();
7674 * Parses a __builtin_expect(, end_error) expression.
7676 static expression_t *parse_builtin_expect(void, end_error)
7678 expression_t *expression
7679 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7681 eat(T___builtin_expect);
7683 expect('(', end_error);
7684 expression->binary.left = parse_assignment_expression();
7685 expect(',', end_error);
7686 expression->binary.right = parse_constant_expression();
7687 expect(')', end_error);
7689 expression->base.type = expression->binary.left->base.type;
7693 return create_invalid_expression();
7698 * Parses a MS assume() expression.
7700 static expression_t *parse_assume(void)
7702 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7706 expect('(', end_error);
7707 add_anchor_token(')');
7708 expression->unary.value = parse_assignment_expression();
7709 rem_anchor_token(')');
7710 expect(')', end_error);
7712 expression->base.type = type_void;
7715 return create_invalid_expression();
7719 * Return the declaration for a given label symbol or create a new one.
7721 * @param symbol the symbol of the label
7723 static label_t *get_label(symbol_t *symbol)
7726 assert(current_function != NULL);
7728 label = get_entity(symbol, NAMESPACE_LABEL);
7729 /* if we found a local label, we already created the declaration */
7730 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7731 if (label->base.parent_scope != current_scope) {
7732 assert(label->base.parent_scope->depth < current_scope->depth);
7733 current_function->goto_to_outer = true;
7735 return &label->label;
7738 label = get_entity(symbol, NAMESPACE_LABEL);
7739 /* if we found a label in the same function, then we already created the
7742 && label->base.parent_scope == ¤t_function->parameters) {
7743 return &label->label;
7746 /* otherwise we need to create a new one */
7747 label = allocate_entity_zero(ENTITY_LABEL);
7748 label->base.namespc = NAMESPACE_LABEL;
7749 label->base.symbol = symbol;
7753 return &label->label;
7757 * Parses a GNU && label address expression.
7759 static expression_t *parse_label_address(void)
7761 source_position_t source_position = token.source_position;
7763 if (token.type != T_IDENTIFIER) {
7764 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7767 symbol_t *symbol = token.v.symbol;
7770 label_t *label = get_label(symbol);
7772 label->address_taken = true;
7774 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7775 expression->base.source_position = source_position;
7777 /* label address is threaten as a void pointer */
7778 expression->base.type = type_void_ptr;
7779 expression->label_address.label = label;
7782 return create_invalid_expression();
7786 * Parse a microsoft __noop expression.
7788 static expression_t *parse_noop_expression(void)
7790 /* the result is a (int)0 */
7791 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7792 cnst->base.type = type_int;
7793 cnst->conste.v.int_value = 0;
7794 cnst->conste.is_ms_noop = true;
7798 if (token.type == '(') {
7799 /* parse arguments */
7801 add_anchor_token(')');
7802 add_anchor_token(',');
7804 if (token.type != ')') {
7806 (void)parse_assignment_expression();
7807 if (token.type != ',')
7813 rem_anchor_token(',');
7814 rem_anchor_token(')');
7815 expect(')', end_error);
7822 * Parses a primary expression.
7824 static expression_t *parse_primary_expression(void)
7826 switch (token.type) {
7827 case T_false: return parse_bool_const(false);
7828 case T_true: return parse_bool_const(true);
7829 case T_INTEGER: return parse_int_const();
7830 case T_CHARACTER_CONSTANT: return parse_character_constant();
7831 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7832 case T_FLOATINGPOINT: return parse_float_const();
7833 case T_STRING_LITERAL:
7834 case T_WIDE_STRING_LITERAL: return parse_string_const();
7835 case T_IDENTIFIER: return parse_reference();
7836 case T___FUNCTION__:
7837 case T___func__: return parse_function_keyword();
7838 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7839 case T___FUNCSIG__: return parse_funcsig_keyword();
7840 case T___FUNCDNAME__: return parse_funcdname_keyword();
7841 case T___builtin_offsetof: return parse_offsetof();
7842 case T___builtin_va_start: return parse_va_start();
7843 case T___builtin_va_arg: return parse_va_arg();
7844 case T___builtin_expect:
7845 case T___builtin_alloca:
7846 case T___builtin_inf:
7847 case T___builtin_inff:
7848 case T___builtin_infl:
7849 case T___builtin_nan:
7850 case T___builtin_nanf:
7851 case T___builtin_nanl:
7852 case T___builtin_huge_val:
7853 case T___builtin_va_end:
7854 case T___builtin_return_address:
7855 case T___builtin_frame_address:
7856 case T___builtin_ffs:
7857 case T___builtin_clz:
7858 case T___builtin_ctz:
7859 case T___builtin_popcount:
7860 case T___builtin_parity:
7861 case T___builtin_prefetch:
7862 case T___builtin_trap: return parse_builtin_symbol();
7863 case T___builtin_isgreater:
7864 case T___builtin_isgreaterequal:
7865 case T___builtin_isless:
7866 case T___builtin_islessequal:
7867 case T___builtin_islessgreater:
7868 case T___builtin_isunordered: return parse_compare_builtin();
7869 case T___builtin_constant_p: return parse_builtin_constant();
7870 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7871 case T__assume: return parse_assume();
7874 return parse_label_address();
7877 case '(': return parse_parenthesized_expression();
7878 case T___noop: return parse_noop_expression();
7881 errorf(HERE, "unexpected token %K, expected an expression", &token);
7882 return create_invalid_expression();
7886 * Check if the expression has the character type and issue a warning then.
7888 static void check_for_char_index_type(const expression_t *expression)
7890 type_t *const type = expression->base.type;
7891 const type_t *const base_type = skip_typeref(type);
7893 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7894 warning.char_subscripts) {
7895 warningf(&expression->base.source_position,
7896 "array subscript has type '%T'", type);
7900 static expression_t *parse_array_expression(expression_t *left)
7902 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7905 add_anchor_token(']');
7907 expression_t *inside = parse_expression();
7909 type_t *const orig_type_left = left->base.type;
7910 type_t *const orig_type_inside = inside->base.type;
7912 type_t *const type_left = skip_typeref(orig_type_left);
7913 type_t *const type_inside = skip_typeref(orig_type_inside);
7915 type_t *return_type;
7916 array_access_expression_t *array_access = &expression->array_access;
7917 if (is_type_pointer(type_left)) {
7918 return_type = type_left->pointer.points_to;
7919 array_access->array_ref = left;
7920 array_access->index = inside;
7921 check_for_char_index_type(inside);
7922 } else if (is_type_pointer(type_inside)) {
7923 return_type = type_inside->pointer.points_to;
7924 array_access->array_ref = inside;
7925 array_access->index = left;
7926 array_access->flipped = true;
7927 check_for_char_index_type(left);
7929 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7931 "array access on object with non-pointer types '%T', '%T'",
7932 orig_type_left, orig_type_inside);
7934 return_type = type_error_type;
7935 array_access->array_ref = left;
7936 array_access->index = inside;
7939 expression->base.type = automatic_type_conversion(return_type);
7941 rem_anchor_token(']');
7942 expect(']', end_error);
7947 static expression_t *parse_typeprop(expression_kind_t const kind)
7949 expression_t *tp_expression = allocate_expression_zero(kind);
7950 tp_expression->base.type = type_size_t;
7952 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7954 /* we only refer to a type property, mark this case */
7955 bool old = in_type_prop;
7956 in_type_prop = true;
7959 expression_t *expression;
7960 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7962 add_anchor_token(')');
7963 orig_type = parse_typename();
7964 rem_anchor_token(')');
7965 expect(')', end_error);
7967 if (token.type == '{') {
7968 /* It was not sizeof(type) after all. It is sizeof of an expression
7969 * starting with a compound literal */
7970 expression = parse_compound_literal(orig_type);
7971 goto typeprop_expression;
7974 expression = parse_sub_expression(PREC_UNARY);
7976 typeprop_expression:
7977 tp_expression->typeprop.tp_expression = expression;
7979 orig_type = revert_automatic_type_conversion(expression);
7980 expression->base.type = orig_type;
7983 tp_expression->typeprop.type = orig_type;
7984 type_t const* const type = skip_typeref(orig_type);
7985 char const* const wrong_type =
7986 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7987 is_type_incomplete(type) ? "incomplete" :
7988 type->kind == TYPE_FUNCTION ? "function designator" :
7989 type->kind == TYPE_BITFIELD ? "bitfield" :
7991 if (wrong_type != NULL) {
7992 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7993 errorf(&tp_expression->base.source_position,
7994 "operand of %s expression must not be of %s type '%T'",
7995 what, wrong_type, orig_type);
8000 return tp_expression;
8003 static expression_t *parse_sizeof(void)
8005 return parse_typeprop(EXPR_SIZEOF);
8008 static expression_t *parse_alignof(void)
8010 return parse_typeprop(EXPR_ALIGNOF);
8013 static expression_t *parse_select_expression(expression_t *compound)
8015 expression_t *select = allocate_expression_zero(EXPR_SELECT);
8016 select->select.compound = compound;
8018 assert(token.type == '.' || token.type == T_MINUSGREATER);
8019 bool is_pointer = (token.type == T_MINUSGREATER);
8022 if (token.type != T_IDENTIFIER) {
8023 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
8026 symbol_t *symbol = token.v.symbol;
8029 type_t *const orig_type = compound->base.type;
8030 type_t *const type = skip_typeref(orig_type);
8033 bool saw_error = false;
8034 if (is_type_pointer(type)) {
8037 "request for member '%Y' in something not a struct or union, but '%T'",
8041 type_left = skip_typeref(type->pointer.points_to);
8043 if (is_pointer && is_type_valid(type)) {
8044 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
8051 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
8052 type_left->kind == TYPE_COMPOUND_UNION) {
8053 compound_t *compound = type_left->compound.compound;
8055 if (!compound->complete) {
8056 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
8058 goto create_error_entry;
8061 entry = find_compound_entry(compound, symbol);
8062 if (entry == NULL) {
8063 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
8064 goto create_error_entry;
8067 if (is_type_valid(type_left) && !saw_error) {
8069 "request for member '%Y' in something not a struct or union, but '%T'",
8073 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
8076 assert(is_declaration(entry));
8077 select->select.compound_entry = entry;
8079 type_t *entry_type = entry->declaration.type;
8081 = get_qualified_type(entry_type, type_left->base.qualifiers);
8083 /* we always do the auto-type conversions; the & and sizeof parser contains
8084 * code to revert this! */
8085 select->base.type = automatic_type_conversion(res_type);
8087 type_t *skipped = skip_typeref(res_type);
8088 if (skipped->kind == TYPE_BITFIELD) {
8089 select->base.type = skipped->bitfield.base_type;
8095 static void check_call_argument(const function_parameter_t *parameter,
8096 call_argument_t *argument, unsigned pos)
8098 type_t *expected_type = parameter->type;
8099 type_t *expected_type_skip = skip_typeref(expected_type);
8100 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
8101 expression_t *arg_expr = argument->expression;
8102 type_t *arg_type = skip_typeref(arg_expr->base.type);
8104 /* handle transparent union gnu extension */
8105 if (is_type_union(expected_type_skip)
8106 && (expected_type_skip->base.modifiers
8107 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
8108 compound_t *union_decl = expected_type_skip->compound.compound;
8109 type_t *best_type = NULL;
8110 entity_t *entry = union_decl->members.entities;
8111 for ( ; entry != NULL; entry = entry->base.next) {
8112 assert(is_declaration(entry));
8113 type_t *decl_type = entry->declaration.type;
8114 error = semantic_assign(decl_type, arg_expr);
8115 if (error == ASSIGN_ERROR_INCOMPATIBLE
8116 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
8119 if (error == ASSIGN_SUCCESS) {
8120 best_type = decl_type;
8121 } else if (best_type == NULL) {
8122 best_type = decl_type;
8126 if (best_type != NULL) {
8127 expected_type = best_type;
8131 error = semantic_assign(expected_type, arg_expr);
8132 argument->expression = create_implicit_cast(argument->expression,
8135 if (error != ASSIGN_SUCCESS) {
8136 /* report exact scope in error messages (like "in argument 3") */
8138 snprintf(buf, sizeof(buf), "call argument %u", pos);
8139 report_assign_error(error, expected_type, arg_expr, buf,
8140 &arg_expr->base.source_position);
8141 } else if (warning.traditional || warning.conversion) {
8142 type_t *const promoted_type = get_default_promoted_type(arg_type);
8143 if (!types_compatible(expected_type_skip, promoted_type) &&
8144 !types_compatible(expected_type_skip, type_void_ptr) &&
8145 !types_compatible(type_void_ptr, promoted_type)) {
8146 /* Deliberately show the skipped types in this warning */
8147 warningf(&arg_expr->base.source_position,
8148 "passing call argument %u as '%T' rather than '%T' due to prototype",
8149 pos, expected_type_skip, promoted_type);
8155 * Handle the semantic restrictions of builtin calls
8157 static void handle_builtin_argument_restrictions(call_expression_t *call) {
8158 switch (call->function->builtin_symbol.symbol->ID) {
8159 case T___builtin_return_address:
8160 case T___builtin_frame_address: {
8161 /* argument must be constant */
8162 call_argument_t *argument = call->arguments;
8164 if (! is_constant_expression(argument->expression)) {
8165 errorf(&call->base.source_position,
8166 "argument of '%Y' must be a constant expression",
8167 call->function->builtin_symbol.symbol);
8171 case T___builtin_prefetch: {
8172 /* second and third argument must be constant if existent */
8173 call_argument_t *rw = call->arguments->next;
8174 call_argument_t *locality = NULL;
8177 if (! is_constant_expression(rw->expression)) {
8178 errorf(&call->base.source_position,
8179 "second argument of '%Y' must be a constant expression",
8180 call->function->builtin_symbol.symbol);
8182 locality = rw->next;
8184 if (locality != NULL) {
8185 if (! is_constant_expression(locality->expression)) {
8186 errorf(&call->base.source_position,
8187 "third argument of '%Y' must be a constant expression",
8188 call->function->builtin_symbol.symbol);
8190 locality = rw->next;
8200 * Parse a call expression, ie. expression '( ... )'.
8202 * @param expression the function address
8204 static expression_t *parse_call_expression(expression_t *expression)
8206 expression_t *result = allocate_expression_zero(EXPR_CALL);
8207 call_expression_t *call = &result->call;
8208 call->function = expression;
8210 type_t *const orig_type = expression->base.type;
8211 type_t *const type = skip_typeref(orig_type);
8213 function_type_t *function_type = NULL;
8214 if (is_type_pointer(type)) {
8215 type_t *const to_type = skip_typeref(type->pointer.points_to);
8217 if (is_type_function(to_type)) {
8218 function_type = &to_type->function;
8219 call->base.type = function_type->return_type;
8223 if (function_type == NULL && is_type_valid(type)) {
8224 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8227 /* parse arguments */
8229 add_anchor_token(')');
8230 add_anchor_token(',');
8232 if (token.type != ')') {
8233 call_argument_t *last_argument = NULL;
8236 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8238 argument->expression = parse_assignment_expression();
8239 if (last_argument == NULL) {
8240 call->arguments = argument;
8242 last_argument->next = argument;
8244 last_argument = argument;
8246 if (token.type != ',')
8251 rem_anchor_token(',');
8252 rem_anchor_token(')');
8253 expect(')', end_error);
8255 if (function_type == NULL)
8258 function_parameter_t *parameter = function_type->parameters;
8259 call_argument_t *argument = call->arguments;
8260 if (!function_type->unspecified_parameters) {
8261 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8262 parameter = parameter->next, argument = argument->next) {
8263 check_call_argument(parameter, argument, ++pos);
8266 if (parameter != NULL) {
8267 errorf(HERE, "too few arguments to function '%E'", expression);
8268 } else if (argument != NULL && !function_type->variadic) {
8269 errorf(HERE, "too many arguments to function '%E'", expression);
8273 /* do default promotion */
8274 for (; argument != NULL; argument = argument->next) {
8275 type_t *type = argument->expression->base.type;
8277 type = get_default_promoted_type(type);
8279 argument->expression
8280 = create_implicit_cast(argument->expression, type);
8283 check_format(&result->call);
8285 if (warning.aggregate_return &&
8286 is_type_compound(skip_typeref(function_type->return_type))) {
8287 warningf(&result->base.source_position,
8288 "function call has aggregate value");
8291 if (call->function->kind == EXPR_BUILTIN_SYMBOL) {
8292 handle_builtin_argument_restrictions(&result->call);
8299 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8301 static bool same_compound_type(const type_t *type1, const type_t *type2)
8304 is_type_compound(type1) &&
8305 type1->kind == type2->kind &&
8306 type1->compound.compound == type2->compound.compound;
8309 static expression_t const *get_reference_address(expression_t const *expr)
8311 bool regular_take_address = true;
8313 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8314 expr = expr->unary.value;
8316 regular_take_address = false;
8319 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8322 expr = expr->unary.value;
8325 if (expr->kind != EXPR_REFERENCE)
8328 /* special case for functions which are automatically converted to a
8329 * pointer to function without an extra TAKE_ADDRESS operation */
8330 if (!regular_take_address &&
8331 expr->reference.entity->kind != ENTITY_FUNCTION) {
8338 static void warn_reference_address_as_bool(expression_t const* expr)
8340 if (!warning.address)
8343 expr = get_reference_address(expr);
8345 warningf(&expr->base.source_position,
8346 "the address of '%Y' will always evaluate as 'true'",
8347 expr->reference.entity->base.symbol);
8351 static void warn_assignment_in_condition(const expression_t *const expr)
8353 if (!warning.parentheses)
8355 if (expr->base.kind != EXPR_BINARY_ASSIGN)
8357 if (expr->base.parenthesized)
8359 warningf(&expr->base.source_position,
8360 "suggest parentheses around assignment used as truth value");
8363 static void semantic_condition(expression_t const *const expr,
8364 char const *const context)
8366 type_t *const type = skip_typeref(expr->base.type);
8367 if (is_type_scalar(type)) {
8368 warn_reference_address_as_bool(expr);
8369 warn_assignment_in_condition(expr);
8370 } else if (is_type_valid(type)) {
8371 errorf(&expr->base.source_position,
8372 "%s must have scalar type", context);
8377 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8379 * @param expression the conditional expression
8381 static expression_t *parse_conditional_expression(expression_t *expression)
8383 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8385 conditional_expression_t *conditional = &result->conditional;
8386 conditional->condition = expression;
8389 add_anchor_token(':');
8391 /* §6.5.15:2 The first operand shall have scalar type. */
8392 semantic_condition(expression, "condition of conditional operator");
8394 expression_t *true_expression = expression;
8395 bool gnu_cond = false;
8396 if (GNU_MODE && token.type == ':') {
8399 true_expression = parse_expression();
8401 rem_anchor_token(':');
8402 expect(':', end_error);
8404 expression_t *false_expression =
8405 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8407 type_t *const orig_true_type = true_expression->base.type;
8408 type_t *const orig_false_type = false_expression->base.type;
8409 type_t *const true_type = skip_typeref(orig_true_type);
8410 type_t *const false_type = skip_typeref(orig_false_type);
8413 type_t *result_type;
8414 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8415 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8416 /* ISO/IEC 14882:1998(E) §5.16:2 */
8417 if (true_expression->kind == EXPR_UNARY_THROW) {
8418 result_type = false_type;
8419 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8420 result_type = true_type;
8422 if (warning.other && (
8423 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8424 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8426 warningf(&conditional->base.source_position,
8427 "ISO C forbids conditional expression with only one void side");
8429 result_type = type_void;
8431 } else if (is_type_arithmetic(true_type)
8432 && is_type_arithmetic(false_type)) {
8433 result_type = semantic_arithmetic(true_type, false_type);
8435 true_expression = create_implicit_cast(true_expression, result_type);
8436 false_expression = create_implicit_cast(false_expression, result_type);
8438 conditional->true_expression = true_expression;
8439 conditional->false_expression = false_expression;
8440 conditional->base.type = result_type;
8441 } else if (same_compound_type(true_type, false_type)) {
8442 /* just take 1 of the 2 types */
8443 result_type = true_type;
8444 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8445 type_t *pointer_type;
8447 expression_t *other_expression;
8448 if (is_type_pointer(true_type) &&
8449 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8450 pointer_type = true_type;
8451 other_type = false_type;
8452 other_expression = false_expression;
8454 pointer_type = false_type;
8455 other_type = true_type;
8456 other_expression = true_expression;
8459 if (is_null_pointer_constant(other_expression)) {
8460 result_type = pointer_type;
8461 } else if (is_type_pointer(other_type)) {
8462 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8463 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8466 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8467 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8469 } else if (types_compatible(get_unqualified_type(to1),
8470 get_unqualified_type(to2))) {
8473 if (warning.other) {
8474 warningf(&conditional->base.source_position,
8475 "pointer types '%T' and '%T' in conditional expression are incompatible",
8476 true_type, false_type);
8481 type_t *const type =
8482 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8483 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8484 } else if (is_type_integer(other_type)) {
8485 if (warning.other) {
8486 warningf(&conditional->base.source_position,
8487 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8489 result_type = pointer_type;
8491 if (is_type_valid(other_type)) {
8492 type_error_incompatible("while parsing conditional",
8493 &expression->base.source_position, true_type, false_type);
8495 result_type = type_error_type;
8498 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8499 type_error_incompatible("while parsing conditional",
8500 &conditional->base.source_position, true_type,
8503 result_type = type_error_type;
8506 conditional->true_expression
8507 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8508 conditional->false_expression
8509 = create_implicit_cast(false_expression, result_type);
8510 conditional->base.type = result_type;
8515 * Parse an extension expression.
8517 static expression_t *parse_extension(void)
8519 eat(T___extension__);
8521 bool old_gcc_extension = in_gcc_extension;
8522 in_gcc_extension = true;
8523 expression_t *expression = parse_sub_expression(PREC_UNARY);
8524 in_gcc_extension = old_gcc_extension;
8529 * Parse a __builtin_classify_type() expression.
8531 static expression_t *parse_builtin_classify_type(void)
8533 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8534 result->base.type = type_int;
8536 eat(T___builtin_classify_type);
8538 expect('(', end_error);
8539 add_anchor_token(')');
8540 expression_t *expression = parse_expression();
8541 rem_anchor_token(')');
8542 expect(')', end_error);
8543 result->classify_type.type_expression = expression;
8547 return create_invalid_expression();
8551 * Parse a delete expression
8552 * ISO/IEC 14882:1998(E) §5.3.5
8554 static expression_t *parse_delete(void)
8556 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8557 result->base.type = type_void;
8561 if (token.type == '[') {
8563 result->kind = EXPR_UNARY_DELETE_ARRAY;
8564 expect(']', end_error);
8568 expression_t *const value = parse_sub_expression(PREC_CAST);
8569 result->unary.value = value;
8571 type_t *const type = skip_typeref(value->base.type);
8572 if (!is_type_pointer(type)) {
8573 if (is_type_valid(type)) {
8574 errorf(&value->base.source_position,
8575 "operand of delete must have pointer type");
8577 } else if (warning.other &&
8578 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8579 warningf(&value->base.source_position,
8580 "deleting 'void*' is undefined");
8587 * Parse a throw expression
8588 * ISO/IEC 14882:1998(E) §15:1
8590 static expression_t *parse_throw(void)
8592 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8593 result->base.type = type_void;
8597 expression_t *value = NULL;
8598 switch (token.type) {
8600 value = parse_assignment_expression();
8601 /* ISO/IEC 14882:1998(E) §15.1:3 */
8602 type_t *const orig_type = value->base.type;
8603 type_t *const type = skip_typeref(orig_type);
8604 if (is_type_incomplete(type)) {
8605 errorf(&value->base.source_position,
8606 "cannot throw object of incomplete type '%T'", orig_type);
8607 } else if (is_type_pointer(type)) {
8608 type_t *const points_to = skip_typeref(type->pointer.points_to);
8609 if (is_type_incomplete(points_to) &&
8610 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8611 errorf(&value->base.source_position,
8612 "cannot throw pointer to incomplete type '%T'", orig_type);
8620 result->unary.value = value;
8625 static bool check_pointer_arithmetic(const source_position_t *source_position,
8626 type_t *pointer_type,
8627 type_t *orig_pointer_type)
8629 type_t *points_to = pointer_type->pointer.points_to;
8630 points_to = skip_typeref(points_to);
8632 if (is_type_incomplete(points_to)) {
8633 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8634 errorf(source_position,
8635 "arithmetic with pointer to incomplete type '%T' not allowed",
8638 } else if (warning.pointer_arith) {
8639 warningf(source_position,
8640 "pointer of type '%T' used in arithmetic",
8643 } else if (is_type_function(points_to)) {
8645 errorf(source_position,
8646 "arithmetic with pointer to function type '%T' not allowed",
8649 } else if (warning.pointer_arith) {
8650 warningf(source_position,
8651 "pointer to a function '%T' used in arithmetic",
8658 static bool is_lvalue(const expression_t *expression)
8660 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8661 switch (expression->kind) {
8662 case EXPR_ARRAY_ACCESS:
8663 case EXPR_COMPOUND_LITERAL:
8664 case EXPR_REFERENCE:
8666 case EXPR_UNARY_DEREFERENCE:
8670 type_t *type = skip_typeref(expression->base.type);
8672 /* ISO/IEC 14882:1998(E) §3.10:3 */
8673 is_type_reference(type) ||
8674 /* Claim it is an lvalue, if the type is invalid. There was a parse
8675 * error before, which maybe prevented properly recognizing it as
8677 !is_type_valid(type);
8682 static void semantic_incdec(unary_expression_t *expression)
8684 type_t *const orig_type = expression->value->base.type;
8685 type_t *const type = skip_typeref(orig_type);
8686 if (is_type_pointer(type)) {
8687 if (!check_pointer_arithmetic(&expression->base.source_position,
8691 } else if (!is_type_real(type) && is_type_valid(type)) {
8692 /* TODO: improve error message */
8693 errorf(&expression->base.source_position,
8694 "operation needs an arithmetic or pointer type");
8697 if (!is_lvalue(expression->value)) {
8698 /* TODO: improve error message */
8699 errorf(&expression->base.source_position, "lvalue required as operand");
8701 expression->base.type = orig_type;
8704 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8706 type_t *const orig_type = expression->value->base.type;
8707 type_t *const type = skip_typeref(orig_type);
8708 if (!is_type_arithmetic(type)) {
8709 if (is_type_valid(type)) {
8710 /* TODO: improve error message */
8711 errorf(&expression->base.source_position,
8712 "operation needs an arithmetic type");
8717 expression->base.type = orig_type;
8720 static void semantic_unexpr_plus(unary_expression_t *expression)
8722 semantic_unexpr_arithmetic(expression);
8723 if (warning.traditional)
8724 warningf(&expression->base.source_position,
8725 "traditional C rejects the unary plus operator");
8728 static void semantic_not(unary_expression_t *expression)
8730 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8731 semantic_condition(expression->value, "operand of !");
8732 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8735 static void semantic_unexpr_integer(unary_expression_t *expression)
8737 type_t *const orig_type = expression->value->base.type;
8738 type_t *const type = skip_typeref(orig_type);
8739 if (!is_type_integer(type)) {
8740 if (is_type_valid(type)) {
8741 errorf(&expression->base.source_position,
8742 "operand of ~ must be of integer type");
8747 expression->base.type = orig_type;
8750 static void semantic_dereference(unary_expression_t *expression)
8752 type_t *const orig_type = expression->value->base.type;
8753 type_t *const type = skip_typeref(orig_type);
8754 if (!is_type_pointer(type)) {
8755 if (is_type_valid(type)) {
8756 errorf(&expression->base.source_position,
8757 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8762 type_t *result_type = type->pointer.points_to;
8763 result_type = automatic_type_conversion(result_type);
8764 expression->base.type = result_type;
8768 * Record that an address is taken (expression represents an lvalue).
8770 * @param expression the expression
8771 * @param may_be_register if true, the expression might be an register
8773 static void set_address_taken(expression_t *expression, bool may_be_register)
8775 if (expression->kind != EXPR_REFERENCE)
8778 entity_t *const entity = expression->reference.entity;
8780 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8783 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8784 && !may_be_register) {
8785 errorf(&expression->base.source_position,
8786 "address of register %s '%Y' requested",
8787 get_entity_kind_name(entity->kind), entity->base.symbol);
8790 if (entity->kind == ENTITY_VARIABLE) {
8791 entity->variable.address_taken = true;
8793 assert(entity->kind == ENTITY_PARAMETER);
8794 entity->parameter.address_taken = true;
8799 * Check the semantic of the address taken expression.
8801 static void semantic_take_addr(unary_expression_t *expression)
8803 expression_t *value = expression->value;
8804 value->base.type = revert_automatic_type_conversion(value);
8806 type_t *orig_type = value->base.type;
8807 type_t *type = skip_typeref(orig_type);
8808 if (!is_type_valid(type))
8812 if (!is_lvalue(value)) {
8813 errorf(&expression->base.source_position, "'&' requires an lvalue");
8815 if (type->kind == TYPE_BITFIELD) {
8816 errorf(&expression->base.source_position,
8817 "'&' not allowed on object with bitfield type '%T'",
8821 set_address_taken(value, false);
8823 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8826 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8827 static expression_t *parse_##unexpression_type(void) \
8829 expression_t *unary_expression \
8830 = allocate_expression_zero(unexpression_type); \
8832 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8834 sfunc(&unary_expression->unary); \
8836 return unary_expression; \
8839 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8840 semantic_unexpr_arithmetic)
8841 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8842 semantic_unexpr_plus)
8843 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8845 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8846 semantic_dereference)
8847 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8849 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8850 semantic_unexpr_integer)
8851 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8853 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8856 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8858 static expression_t *parse_##unexpression_type(expression_t *left) \
8860 expression_t *unary_expression \
8861 = allocate_expression_zero(unexpression_type); \
8863 unary_expression->unary.value = left; \
8865 sfunc(&unary_expression->unary); \
8867 return unary_expression; \
8870 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8871 EXPR_UNARY_POSTFIX_INCREMENT,
8873 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8874 EXPR_UNARY_POSTFIX_DECREMENT,
8877 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8879 /* TODO: handle complex + imaginary types */
8881 type_left = get_unqualified_type(type_left);
8882 type_right = get_unqualified_type(type_right);
8884 /* §6.3.1.8 Usual arithmetic conversions */
8885 if (type_left == type_long_double || type_right == type_long_double) {
8886 return type_long_double;
8887 } else if (type_left == type_double || type_right == type_double) {
8889 } else if (type_left == type_float || type_right == type_float) {
8893 type_left = promote_integer(type_left);
8894 type_right = promote_integer(type_right);
8896 if (type_left == type_right)
8899 bool const signed_left = is_type_signed(type_left);
8900 bool const signed_right = is_type_signed(type_right);
8901 int const rank_left = get_rank(type_left);
8902 int const rank_right = get_rank(type_right);
8904 if (signed_left == signed_right)
8905 return rank_left >= rank_right ? type_left : type_right;
8914 u_rank = rank_right;
8915 u_type = type_right;
8917 s_rank = rank_right;
8918 s_type = type_right;
8923 if (u_rank >= s_rank)
8926 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8928 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8929 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8933 case ATOMIC_TYPE_INT: return type_unsigned_int;
8934 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8935 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8937 default: panic("invalid atomic type");
8942 * Check the semantic restrictions for a binary expression.
8944 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8946 expression_t *const left = expression->left;
8947 expression_t *const right = expression->right;
8948 type_t *const orig_type_left = left->base.type;
8949 type_t *const orig_type_right = right->base.type;
8950 type_t *const type_left = skip_typeref(orig_type_left);
8951 type_t *const type_right = skip_typeref(orig_type_right);
8953 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8954 /* TODO: improve error message */
8955 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8956 errorf(&expression->base.source_position,
8957 "operation needs arithmetic types");
8962 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8963 expression->left = create_implicit_cast(left, arithmetic_type);
8964 expression->right = create_implicit_cast(right, arithmetic_type);
8965 expression->base.type = arithmetic_type;
8968 static void warn_div_by_zero(binary_expression_t const *const expression)
8970 if (!warning.div_by_zero ||
8971 !is_type_integer(expression->base.type))
8974 expression_t const *const right = expression->right;
8975 /* The type of the right operand can be different for /= */
8976 if (is_type_integer(right->base.type) &&
8977 is_constant_expression(right) &&
8978 fold_constant(right) == 0) {
8979 warningf(&expression->base.source_position, "division by zero");
8984 * Check the semantic restrictions for a div/mod expression.
8986 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8988 semantic_binexpr_arithmetic(expression);
8989 warn_div_by_zero(expression);
8992 static void warn_addsub_in_shift(const expression_t *const expr)
8994 if (expr->base.parenthesized)
8998 switch (expr->kind) {
8999 case EXPR_BINARY_ADD: op = '+'; break;
9000 case EXPR_BINARY_SUB: op = '-'; break;
9004 warningf(&expr->base.source_position,
9005 "suggest parentheses around '%c' inside shift", op);
9008 static void semantic_shift_op(binary_expression_t *expression)
9010 expression_t *const left = expression->left;
9011 expression_t *const right = expression->right;
9012 type_t *const orig_type_left = left->base.type;
9013 type_t *const orig_type_right = right->base.type;
9014 type_t * type_left = skip_typeref(orig_type_left);
9015 type_t * type_right = skip_typeref(orig_type_right);
9017 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
9018 /* TODO: improve error message */
9019 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9020 errorf(&expression->base.source_position,
9021 "operands of shift operation must have integer types");
9026 if (warning.parentheses) {
9027 warn_addsub_in_shift(left);
9028 warn_addsub_in_shift(right);
9031 type_left = promote_integer(type_left);
9032 type_right = promote_integer(type_right);
9034 expression->left = create_implicit_cast(left, type_left);
9035 expression->right = create_implicit_cast(right, type_right);
9036 expression->base.type = type_left;
9039 static void semantic_add(binary_expression_t *expression)
9041 expression_t *const left = expression->left;
9042 expression_t *const right = expression->right;
9043 type_t *const orig_type_left = left->base.type;
9044 type_t *const orig_type_right = right->base.type;
9045 type_t *const type_left = skip_typeref(orig_type_left);
9046 type_t *const type_right = skip_typeref(orig_type_right);
9049 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9050 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9051 expression->left = create_implicit_cast(left, arithmetic_type);
9052 expression->right = create_implicit_cast(right, arithmetic_type);
9053 expression->base.type = arithmetic_type;
9054 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9055 check_pointer_arithmetic(&expression->base.source_position,
9056 type_left, orig_type_left);
9057 expression->base.type = type_left;
9058 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
9059 check_pointer_arithmetic(&expression->base.source_position,
9060 type_right, orig_type_right);
9061 expression->base.type = type_right;
9062 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9063 errorf(&expression->base.source_position,
9064 "invalid operands to binary + ('%T', '%T')",
9065 orig_type_left, orig_type_right);
9069 static void semantic_sub(binary_expression_t *expression)
9071 expression_t *const left = expression->left;
9072 expression_t *const right = expression->right;
9073 type_t *const orig_type_left = left->base.type;
9074 type_t *const orig_type_right = right->base.type;
9075 type_t *const type_left = skip_typeref(orig_type_left);
9076 type_t *const type_right = skip_typeref(orig_type_right);
9077 source_position_t const *const pos = &expression->base.source_position;
9080 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9081 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9082 expression->left = create_implicit_cast(left, arithmetic_type);
9083 expression->right = create_implicit_cast(right, arithmetic_type);
9084 expression->base.type = arithmetic_type;
9085 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9086 check_pointer_arithmetic(&expression->base.source_position,
9087 type_left, orig_type_left);
9088 expression->base.type = type_left;
9089 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9090 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
9091 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
9092 if (!types_compatible(unqual_left, unqual_right)) {
9094 "subtracting pointers to incompatible types '%T' and '%T'",
9095 orig_type_left, orig_type_right);
9096 } else if (!is_type_object(unqual_left)) {
9097 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
9098 errorf(pos, "subtracting pointers to non-object types '%T'",
9100 } else if (warning.other) {
9101 warningf(pos, "subtracting pointers to void");
9104 expression->base.type = type_ptrdiff_t;
9105 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9106 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
9107 orig_type_left, orig_type_right);
9111 static void warn_string_literal_address(expression_t const* expr)
9113 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
9114 expr = expr->unary.value;
9115 if (expr->kind != EXPR_UNARY_DEREFERENCE)
9117 expr = expr->unary.value;
9120 if (expr->kind == EXPR_STRING_LITERAL ||
9121 expr->kind == EXPR_WIDE_STRING_LITERAL) {
9122 warningf(&expr->base.source_position,
9123 "comparison with string literal results in unspecified behaviour");
9127 static void warn_comparison_in_comparison(const expression_t *const expr)
9129 if (expr->base.parenthesized)
9131 switch (expr->base.kind) {
9132 case EXPR_BINARY_LESS:
9133 case EXPR_BINARY_GREATER:
9134 case EXPR_BINARY_LESSEQUAL:
9135 case EXPR_BINARY_GREATEREQUAL:
9136 case EXPR_BINARY_NOTEQUAL:
9137 case EXPR_BINARY_EQUAL:
9138 warningf(&expr->base.source_position,
9139 "comparisons like 'x <= y < z' do not have their mathematical meaning");
9146 static bool maybe_negative(expression_t const *const expr)
9149 !is_constant_expression(expr) ||
9150 fold_constant(expr) < 0;
9154 * Check the semantics of comparison expressions.
9156 * @param expression The expression to check.
9158 static void semantic_comparison(binary_expression_t *expression)
9160 expression_t *left = expression->left;
9161 expression_t *right = expression->right;
9163 if (warning.address) {
9164 warn_string_literal_address(left);
9165 warn_string_literal_address(right);
9167 expression_t const* const func_left = get_reference_address(left);
9168 if (func_left != NULL && is_null_pointer_constant(right)) {
9169 warningf(&expression->base.source_position,
9170 "the address of '%Y' will never be NULL",
9171 func_left->reference.entity->base.symbol);
9174 expression_t const* const func_right = get_reference_address(right);
9175 if (func_right != NULL && is_null_pointer_constant(right)) {
9176 warningf(&expression->base.source_position,
9177 "the address of '%Y' will never be NULL",
9178 func_right->reference.entity->base.symbol);
9182 if (warning.parentheses) {
9183 warn_comparison_in_comparison(left);
9184 warn_comparison_in_comparison(right);
9187 type_t *orig_type_left = left->base.type;
9188 type_t *orig_type_right = right->base.type;
9189 type_t *type_left = skip_typeref(orig_type_left);
9190 type_t *type_right = skip_typeref(orig_type_right);
9192 /* TODO non-arithmetic types */
9193 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9194 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9196 /* test for signed vs unsigned compares */
9197 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
9198 bool const signed_left = is_type_signed(type_left);
9199 bool const signed_right = is_type_signed(type_right);
9200 if (signed_left != signed_right) {
9201 /* FIXME long long needs better const folding magic */
9202 /* TODO check whether constant value can be represented by other type */
9203 if ((signed_left && maybe_negative(left)) ||
9204 (signed_right && maybe_negative(right))) {
9205 warningf(&expression->base.source_position,
9206 "comparison between signed and unsigned");
9211 expression->left = create_implicit_cast(left, arithmetic_type);
9212 expression->right = create_implicit_cast(right, arithmetic_type);
9213 expression->base.type = arithmetic_type;
9214 if (warning.float_equal &&
9215 (expression->base.kind == EXPR_BINARY_EQUAL ||
9216 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
9217 is_type_float(arithmetic_type)) {
9218 warningf(&expression->base.source_position,
9219 "comparing floating point with == or != is unsafe");
9221 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
9222 /* TODO check compatibility */
9223 } else if (is_type_pointer(type_left)) {
9224 expression->right = create_implicit_cast(right, type_left);
9225 } else if (is_type_pointer(type_right)) {
9226 expression->left = create_implicit_cast(left, type_right);
9227 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9228 type_error_incompatible("invalid operands in comparison",
9229 &expression->base.source_position,
9230 type_left, type_right);
9232 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9236 * Checks if a compound type has constant fields.
9238 static bool has_const_fields(const compound_type_t *type)
9240 compound_t *compound = type->compound;
9241 entity_t *entry = compound->members.entities;
9243 for (; entry != NULL; entry = entry->base.next) {
9244 if (!is_declaration(entry))
9247 const type_t *decl_type = skip_typeref(entry->declaration.type);
9248 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9255 static bool is_valid_assignment_lhs(expression_t const* const left)
9257 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9258 type_t *const type_left = skip_typeref(orig_type_left);
9260 if (!is_lvalue(left)) {
9261 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9266 if (left->kind == EXPR_REFERENCE
9267 && left->reference.entity->kind == ENTITY_FUNCTION) {
9268 errorf(HERE, "cannot assign to function '%E'", left);
9272 if (is_type_array(type_left)) {
9273 errorf(HERE, "cannot assign to array '%E'", left);
9276 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9277 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9281 if (is_type_incomplete(type_left)) {
9282 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9283 left, orig_type_left);
9286 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9287 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9288 left, orig_type_left);
9295 static void semantic_arithmetic_assign(binary_expression_t *expression)
9297 expression_t *left = expression->left;
9298 expression_t *right = expression->right;
9299 type_t *orig_type_left = left->base.type;
9300 type_t *orig_type_right = right->base.type;
9302 if (!is_valid_assignment_lhs(left))
9305 type_t *type_left = skip_typeref(orig_type_left);
9306 type_t *type_right = skip_typeref(orig_type_right);
9308 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9309 /* TODO: improve error message */
9310 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9311 errorf(&expression->base.source_position,
9312 "operation needs arithmetic types");
9317 /* combined instructions are tricky. We can't create an implicit cast on
9318 * the left side, because we need the uncasted form for the store.
9319 * The ast2firm pass has to know that left_type must be right_type
9320 * for the arithmetic operation and create a cast by itself */
9321 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9322 expression->right = create_implicit_cast(right, arithmetic_type);
9323 expression->base.type = type_left;
9326 static void semantic_divmod_assign(binary_expression_t *expression)
9328 semantic_arithmetic_assign(expression);
9329 warn_div_by_zero(expression);
9332 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9334 expression_t *const left = expression->left;
9335 expression_t *const right = expression->right;
9336 type_t *const orig_type_left = left->base.type;
9337 type_t *const orig_type_right = right->base.type;
9338 type_t *const type_left = skip_typeref(orig_type_left);
9339 type_t *const type_right = skip_typeref(orig_type_right);
9341 if (!is_valid_assignment_lhs(left))
9344 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9345 /* combined instructions are tricky. We can't create an implicit cast on
9346 * the left side, because we need the uncasted form for the store.
9347 * The ast2firm pass has to know that left_type must be right_type
9348 * for the arithmetic operation and create a cast by itself */
9349 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9350 expression->right = create_implicit_cast(right, arithmetic_type);
9351 expression->base.type = type_left;
9352 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9353 check_pointer_arithmetic(&expression->base.source_position,
9354 type_left, orig_type_left);
9355 expression->base.type = type_left;
9356 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9357 errorf(&expression->base.source_position,
9358 "incompatible types '%T' and '%T' in assignment",
9359 orig_type_left, orig_type_right);
9363 static void warn_logical_and_within_or(const expression_t *const expr)
9365 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
9367 if (expr->base.parenthesized)
9369 warningf(&expr->base.source_position,
9370 "suggest parentheses around && within ||");
9374 * Check the semantic restrictions of a logical expression.
9376 static void semantic_logical_op(binary_expression_t *expression)
9378 /* §6.5.13:2 Each of the operands shall have scalar type.
9379 * §6.5.14:2 Each of the operands shall have scalar type. */
9380 semantic_condition(expression->left, "left operand of logical operator");
9381 semantic_condition(expression->right, "right operand of logical operator");
9382 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
9383 warning.parentheses) {
9384 warn_logical_and_within_or(expression->left);
9385 warn_logical_and_within_or(expression->right);
9387 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9391 * Check the semantic restrictions of a binary assign expression.
9393 static void semantic_binexpr_assign(binary_expression_t *expression)
9395 expression_t *left = expression->left;
9396 type_t *orig_type_left = left->base.type;
9398 if (!is_valid_assignment_lhs(left))
9401 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9402 report_assign_error(error, orig_type_left, expression->right,
9403 "assignment", &left->base.source_position);
9404 expression->right = create_implicit_cast(expression->right, orig_type_left);
9405 expression->base.type = orig_type_left;
9409 * Determine if the outermost operation (or parts thereof) of the given
9410 * expression has no effect in order to generate a warning about this fact.
9411 * Therefore in some cases this only examines some of the operands of the
9412 * expression (see comments in the function and examples below).
9414 * f() + 23; // warning, because + has no effect
9415 * x || f(); // no warning, because x controls execution of f()
9416 * x ? y : f(); // warning, because y has no effect
9417 * (void)x; // no warning to be able to suppress the warning
9418 * This function can NOT be used for an "expression has definitely no effect"-
9420 static bool expression_has_effect(const expression_t *const expr)
9422 switch (expr->kind) {
9423 case EXPR_UNKNOWN: break;
9424 case EXPR_INVALID: return true; /* do NOT warn */
9425 case EXPR_REFERENCE: return false;
9426 case EXPR_REFERENCE_ENUM_VALUE: return false;
9427 /* suppress the warning for microsoft __noop operations */
9428 case EXPR_CONST: return expr->conste.is_ms_noop;
9429 case EXPR_CHARACTER_CONSTANT: return false;
9430 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9431 case EXPR_STRING_LITERAL: return false;
9432 case EXPR_WIDE_STRING_LITERAL: return false;
9433 case EXPR_LABEL_ADDRESS: return false;
9436 const call_expression_t *const call = &expr->call;
9437 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9440 switch (call->function->builtin_symbol.symbol->ID) {
9441 case T___builtin_prefetch:
9442 case T___builtin_va_end: return true;
9443 default: return false;
9447 /* Generate the warning if either the left or right hand side of a
9448 * conditional expression has no effect */
9449 case EXPR_CONDITIONAL: {
9450 conditional_expression_t const *const cond = &expr->conditional;
9451 expression_t const *const t = cond->true_expression;
9453 (t == NULL || expression_has_effect(t)) &&
9454 expression_has_effect(cond->false_expression);
9457 case EXPR_SELECT: return false;
9458 case EXPR_ARRAY_ACCESS: return false;
9459 case EXPR_SIZEOF: return false;
9460 case EXPR_CLASSIFY_TYPE: return false;
9461 case EXPR_ALIGNOF: return false;
9463 case EXPR_FUNCNAME: return false;
9464 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9465 case EXPR_BUILTIN_CONSTANT_P: return false;
9466 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
9467 case EXPR_OFFSETOF: return false;
9468 case EXPR_VA_START: return true;
9469 case EXPR_VA_ARG: return true;
9470 case EXPR_STATEMENT: return true; // TODO
9471 case EXPR_COMPOUND_LITERAL: return false;
9473 case EXPR_UNARY_NEGATE: return false;
9474 case EXPR_UNARY_PLUS: return false;
9475 case EXPR_UNARY_BITWISE_NEGATE: return false;
9476 case EXPR_UNARY_NOT: return false;
9477 case EXPR_UNARY_DEREFERENCE: return false;
9478 case EXPR_UNARY_TAKE_ADDRESS: return false;
9479 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9480 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9481 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9482 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9484 /* Treat void casts as if they have an effect in order to being able to
9485 * suppress the warning */
9486 case EXPR_UNARY_CAST: {
9487 type_t *const type = skip_typeref(expr->base.type);
9488 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9491 case EXPR_UNARY_CAST_IMPLICIT: return true;
9492 case EXPR_UNARY_ASSUME: return true;
9493 case EXPR_UNARY_DELETE: return true;
9494 case EXPR_UNARY_DELETE_ARRAY: return true;
9495 case EXPR_UNARY_THROW: return true;
9497 case EXPR_BINARY_ADD: return false;
9498 case EXPR_BINARY_SUB: return false;
9499 case EXPR_BINARY_MUL: return false;
9500 case EXPR_BINARY_DIV: return false;
9501 case EXPR_BINARY_MOD: return false;
9502 case EXPR_BINARY_EQUAL: return false;
9503 case EXPR_BINARY_NOTEQUAL: return false;
9504 case EXPR_BINARY_LESS: return false;
9505 case EXPR_BINARY_LESSEQUAL: return false;
9506 case EXPR_BINARY_GREATER: return false;
9507 case EXPR_BINARY_GREATEREQUAL: return false;
9508 case EXPR_BINARY_BITWISE_AND: return false;
9509 case EXPR_BINARY_BITWISE_OR: return false;
9510 case EXPR_BINARY_BITWISE_XOR: return false;
9511 case EXPR_BINARY_SHIFTLEFT: return false;
9512 case EXPR_BINARY_SHIFTRIGHT: return false;
9513 case EXPR_BINARY_ASSIGN: return true;
9514 case EXPR_BINARY_MUL_ASSIGN: return true;
9515 case EXPR_BINARY_DIV_ASSIGN: return true;
9516 case EXPR_BINARY_MOD_ASSIGN: return true;
9517 case EXPR_BINARY_ADD_ASSIGN: return true;
9518 case EXPR_BINARY_SUB_ASSIGN: return true;
9519 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9520 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9521 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9522 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9523 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9525 /* Only examine the right hand side of && and ||, because the left hand
9526 * side already has the effect of controlling the execution of the right
9528 case EXPR_BINARY_LOGICAL_AND:
9529 case EXPR_BINARY_LOGICAL_OR:
9530 /* Only examine the right hand side of a comma expression, because the left
9531 * hand side has a separate warning */
9532 case EXPR_BINARY_COMMA:
9533 return expression_has_effect(expr->binary.right);
9535 case EXPR_BINARY_ISGREATER: return false;
9536 case EXPR_BINARY_ISGREATEREQUAL: return false;
9537 case EXPR_BINARY_ISLESS: return false;
9538 case EXPR_BINARY_ISLESSEQUAL: return false;
9539 case EXPR_BINARY_ISLESSGREATER: return false;
9540 case EXPR_BINARY_ISUNORDERED: return false;
9543 internal_errorf(HERE, "unexpected expression");
9546 static void semantic_comma(binary_expression_t *expression)
9548 if (warning.unused_value) {
9549 const expression_t *const left = expression->left;
9550 if (!expression_has_effect(left)) {
9551 warningf(&left->base.source_position,
9552 "left-hand operand of comma expression has no effect");
9555 expression->base.type = expression->right->base.type;
9559 * @param prec_r precedence of the right operand
9561 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9562 static expression_t *parse_##binexpression_type(expression_t *left) \
9564 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9565 binexpr->binary.left = left; \
9568 expression_t *right = parse_sub_expression(prec_r); \
9570 binexpr->binary.right = right; \
9571 sfunc(&binexpr->binary); \
9576 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9577 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9578 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9579 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9580 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9581 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9582 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9583 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9584 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9585 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9586 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9587 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9588 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9589 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9590 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9591 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9592 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9593 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9594 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9595 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9596 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9597 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9598 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9599 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9600 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9601 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9602 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9603 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9604 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9605 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9608 static expression_t *parse_sub_expression(precedence_t precedence)
9610 if (token.type < 0) {
9611 return expected_expression_error();
9614 expression_parser_function_t *parser
9615 = &expression_parsers[token.type];
9616 source_position_t source_position = token.source_position;
9619 if (parser->parser != NULL) {
9620 left = parser->parser();
9622 left = parse_primary_expression();
9624 assert(left != NULL);
9625 left->base.source_position = source_position;
9628 if (token.type < 0) {
9629 return expected_expression_error();
9632 parser = &expression_parsers[token.type];
9633 if (parser->infix_parser == NULL)
9635 if (parser->infix_precedence < precedence)
9638 left = parser->infix_parser(left);
9640 assert(left != NULL);
9641 assert(left->kind != EXPR_UNKNOWN);
9642 left->base.source_position = source_position;
9649 * Parse an expression.
9651 static expression_t *parse_expression(void)
9653 return parse_sub_expression(PREC_EXPRESSION);
9657 * Register a parser for a prefix-like operator.
9659 * @param parser the parser function
9660 * @param token_type the token type of the prefix token
9662 static void register_expression_parser(parse_expression_function parser,
9665 expression_parser_function_t *entry = &expression_parsers[token_type];
9667 if (entry->parser != NULL) {
9668 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9669 panic("trying to register multiple expression parsers for a token");
9671 entry->parser = parser;
9675 * Register a parser for an infix operator with given precedence.
9677 * @param parser the parser function
9678 * @param token_type the token type of the infix operator
9679 * @param precedence the precedence of the operator
9681 static void register_infix_parser(parse_expression_infix_function parser,
9682 int token_type, precedence_t precedence)
9684 expression_parser_function_t *entry = &expression_parsers[token_type];
9686 if (entry->infix_parser != NULL) {
9687 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9688 panic("trying to register multiple infix expression parsers for a "
9691 entry->infix_parser = parser;
9692 entry->infix_precedence = precedence;
9696 * Initialize the expression parsers.
9698 static void init_expression_parsers(void)
9700 memset(&expression_parsers, 0, sizeof(expression_parsers));
9702 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9703 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9704 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9705 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9706 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9707 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9708 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9709 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9710 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9711 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9712 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9713 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9714 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9715 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9716 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9717 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9718 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9719 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9720 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9721 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9722 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9723 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9724 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9725 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9726 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9727 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9728 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9729 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9730 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9731 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9732 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9733 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9734 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9735 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9736 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9737 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9738 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9740 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9741 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9742 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9743 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9744 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9745 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9746 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9747 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9748 register_expression_parser(parse_sizeof, T_sizeof);
9749 register_expression_parser(parse_alignof, T___alignof__);
9750 register_expression_parser(parse_extension, T___extension__);
9751 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9752 register_expression_parser(parse_delete, T_delete);
9753 register_expression_parser(parse_throw, T_throw);
9757 * Parse a asm statement arguments specification.
9759 static asm_argument_t *parse_asm_arguments(bool is_out)
9761 asm_argument_t *result = NULL;
9762 asm_argument_t **anchor = &result;
9764 while (token.type == T_STRING_LITERAL || token.type == '[') {
9765 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9766 memset(argument, 0, sizeof(argument[0]));
9768 if (token.type == '[') {
9770 if (token.type != T_IDENTIFIER) {
9771 parse_error_expected("while parsing asm argument",
9772 T_IDENTIFIER, NULL);
9775 argument->symbol = token.v.symbol;
9777 expect(']', end_error);
9780 argument->constraints = parse_string_literals();
9781 expect('(', end_error);
9782 add_anchor_token(')');
9783 expression_t *expression = parse_expression();
9784 rem_anchor_token(')');
9786 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9787 * change size or type representation (e.g. int -> long is ok, but
9788 * int -> float is not) */
9789 if (expression->kind == EXPR_UNARY_CAST) {
9790 type_t *const type = expression->base.type;
9791 type_kind_t const kind = type->kind;
9792 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9795 if (kind == TYPE_ATOMIC) {
9796 atomic_type_kind_t const akind = type->atomic.akind;
9797 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9798 size = get_atomic_type_size(akind);
9800 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9801 size = get_atomic_type_size(get_intptr_kind());
9805 expression_t *const value = expression->unary.value;
9806 type_t *const value_type = value->base.type;
9807 type_kind_t const value_kind = value_type->kind;
9809 unsigned value_flags;
9810 unsigned value_size;
9811 if (value_kind == TYPE_ATOMIC) {
9812 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9813 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9814 value_size = get_atomic_type_size(value_akind);
9815 } else if (value_kind == TYPE_POINTER) {
9816 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9817 value_size = get_atomic_type_size(get_intptr_kind());
9822 if (value_flags != flags || value_size != size)
9826 } while (expression->kind == EXPR_UNARY_CAST);
9830 if (!is_lvalue(expression)) {
9831 errorf(&expression->base.source_position,
9832 "asm output argument is not an lvalue");
9835 if (argument->constraints.begin[0] == '+')
9836 mark_vars_read(expression, NULL);
9838 mark_vars_read(expression, NULL);
9840 argument->expression = expression;
9841 expect(')', end_error);
9843 set_address_taken(expression, true);
9846 anchor = &argument->next;
9848 if (token.type != ',')
9859 * Parse a asm statement clobber specification.
9861 static asm_clobber_t *parse_asm_clobbers(void)
9863 asm_clobber_t *result = NULL;
9864 asm_clobber_t *last = NULL;
9866 while (token.type == T_STRING_LITERAL) {
9867 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9868 clobber->clobber = parse_string_literals();
9871 last->next = clobber;
9877 if (token.type != ',')
9886 * Parse an asm statement.
9888 static statement_t *parse_asm_statement(void)
9890 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9891 asm_statement_t *asm_statement = &statement->asms;
9895 if (token.type == T_volatile) {
9897 asm_statement->is_volatile = true;
9900 expect('(', end_error);
9901 add_anchor_token(')');
9902 add_anchor_token(':');
9903 asm_statement->asm_text = parse_string_literals();
9905 if (token.type != ':') {
9906 rem_anchor_token(':');
9911 asm_statement->outputs = parse_asm_arguments(true);
9912 if (token.type != ':') {
9913 rem_anchor_token(':');
9918 asm_statement->inputs = parse_asm_arguments(false);
9919 if (token.type != ':') {
9920 rem_anchor_token(':');
9923 rem_anchor_token(':');
9926 asm_statement->clobbers = parse_asm_clobbers();
9929 rem_anchor_token(')');
9930 expect(')', end_error);
9931 expect(';', end_error);
9933 if (asm_statement->outputs == NULL) {
9934 /* GCC: An 'asm' instruction without any output operands will be treated
9935 * identically to a volatile 'asm' instruction. */
9936 asm_statement->is_volatile = true;
9941 return create_invalid_statement();
9945 * Parse a case statement.
9947 static statement_t *parse_case_statement(void)
9949 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9950 source_position_t *const pos = &statement->base.source_position;
9954 expression_t *const expression = parse_expression();
9955 statement->case_label.expression = expression;
9956 if (!is_constant_expression(expression)) {
9957 /* This check does not prevent the error message in all cases of an
9958 * prior error while parsing the expression. At least it catches the
9959 * common case of a mistyped enum entry. */
9960 if (is_type_valid(skip_typeref(expression->base.type))) {
9961 errorf(pos, "case label does not reduce to an integer constant");
9963 statement->case_label.is_bad = true;
9965 long const val = fold_constant(expression);
9966 statement->case_label.first_case = val;
9967 statement->case_label.last_case = val;
9971 if (token.type == T_DOTDOTDOT) {
9973 expression_t *const end_range = parse_expression();
9974 statement->case_label.end_range = end_range;
9975 if (!is_constant_expression(end_range)) {
9976 /* This check does not prevent the error message in all cases of an
9977 * prior error while parsing the expression. At least it catches the
9978 * common case of a mistyped enum entry. */
9979 if (is_type_valid(skip_typeref(end_range->base.type))) {
9980 errorf(pos, "case range does not reduce to an integer constant");
9982 statement->case_label.is_bad = true;
9984 long const val = fold_constant(end_range);
9985 statement->case_label.last_case = val;
9987 if (warning.other && val < statement->case_label.first_case) {
9988 statement->case_label.is_empty_range = true;
9989 warningf(pos, "empty range specified");
9995 PUSH_PARENT(statement);
9997 expect(':', end_error);
10000 if (current_switch != NULL) {
10001 if (! statement->case_label.is_bad) {
10002 /* Check for duplicate case values */
10003 case_label_statement_t *c = &statement->case_label;
10004 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
10005 if (l->is_bad || l->is_empty_range || l->expression == NULL)
10008 if (c->last_case < l->first_case || c->first_case > l->last_case)
10011 errorf(pos, "duplicate case value (previously used %P)",
10012 &l->base.source_position);
10016 /* link all cases into the switch statement */
10017 if (current_switch->last_case == NULL) {
10018 current_switch->first_case = &statement->case_label;
10020 current_switch->last_case->next = &statement->case_label;
10022 current_switch->last_case = &statement->case_label;
10024 errorf(pos, "case label not within a switch statement");
10027 statement_t *const inner_stmt = parse_statement();
10028 statement->case_label.statement = inner_stmt;
10029 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10030 errorf(&inner_stmt->base.source_position, "declaration after case label");
10038 * Parse a default statement.
10040 static statement_t *parse_default_statement(void)
10042 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
10046 PUSH_PARENT(statement);
10048 expect(':', end_error);
10049 if (current_switch != NULL) {
10050 const case_label_statement_t *def_label = current_switch->default_label;
10051 if (def_label != NULL) {
10052 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
10053 &def_label->base.source_position);
10055 current_switch->default_label = &statement->case_label;
10057 /* link all cases into the switch statement */
10058 if (current_switch->last_case == NULL) {
10059 current_switch->first_case = &statement->case_label;
10061 current_switch->last_case->next = &statement->case_label;
10063 current_switch->last_case = &statement->case_label;
10066 errorf(&statement->base.source_position,
10067 "'default' label not within a switch statement");
10070 statement_t *const inner_stmt = parse_statement();
10071 statement->case_label.statement = inner_stmt;
10072 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10073 errorf(&inner_stmt->base.source_position, "declaration after default label");
10080 return create_invalid_statement();
10084 * Parse a label statement.
10086 static statement_t *parse_label_statement(void)
10088 assert(token.type == T_IDENTIFIER);
10089 symbol_t *symbol = token.v.symbol;
10090 label_t *label = get_label(symbol);
10092 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
10093 statement->label.label = label;
10097 PUSH_PARENT(statement);
10099 /* if statement is already set then the label is defined twice,
10100 * otherwise it was just mentioned in a goto/local label declaration so far
10102 if (label->statement != NULL) {
10103 errorf(HERE, "duplicate label '%Y' (declared %P)",
10104 symbol, &label->base.source_position);
10106 label->base.source_position = token.source_position;
10107 label->statement = statement;
10112 if (token.type == '}') {
10113 /* TODO only warn? */
10114 if (warning.other && false) {
10115 warningf(HERE, "label at end of compound statement");
10116 statement->label.statement = create_empty_statement();
10118 errorf(HERE, "label at end of compound statement");
10119 statement->label.statement = create_invalid_statement();
10121 } else if (token.type == ';') {
10122 /* Eat an empty statement here, to avoid the warning about an empty
10123 * statement after a label. label:; is commonly used to have a label
10124 * before a closing brace. */
10125 statement->label.statement = create_empty_statement();
10128 statement_t *const inner_stmt = parse_statement();
10129 statement->label.statement = inner_stmt;
10130 if (inner_stmt->kind == STATEMENT_DECLARATION) {
10131 errorf(&inner_stmt->base.source_position, "declaration after label");
10135 /* remember the labels in a list for later checking */
10136 *label_anchor = &statement->label;
10137 label_anchor = &statement->label.next;
10144 * Parse an if statement.
10146 static statement_t *parse_if(void)
10148 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
10152 PUSH_PARENT(statement);
10154 add_anchor_token('{');
10156 expect('(', end_error);
10157 add_anchor_token(')');
10158 expression_t *const expr = parse_expression();
10159 statement->ifs.condition = expr;
10160 /* §6.8.4.1:1 The controlling expression of an if statement shall have
10162 semantic_condition(expr, "condition of 'if'-statment");
10163 mark_vars_read(expr, NULL);
10164 rem_anchor_token(')');
10165 expect(')', end_error);
10168 rem_anchor_token('{');
10170 add_anchor_token(T_else);
10171 statement_t *const true_stmt = parse_statement();
10172 statement->ifs.true_statement = true_stmt;
10173 rem_anchor_token(T_else);
10175 if (token.type == T_else) {
10177 statement->ifs.false_statement = parse_statement();
10178 } else if (warning.parentheses &&
10179 true_stmt->kind == STATEMENT_IF &&
10180 true_stmt->ifs.false_statement != NULL) {
10181 warningf(&true_stmt->base.source_position,
10182 "suggest explicit braces to avoid ambiguous 'else'");
10190 * Check that all enums are handled in a switch.
10192 * @param statement the switch statement to check
10194 static void check_enum_cases(const switch_statement_t *statement)
10196 const type_t *type = skip_typeref(statement->expression->base.type);
10197 if (! is_type_enum(type))
10199 const enum_type_t *enumt = &type->enumt;
10201 /* if we have a default, no warnings */
10202 if (statement->default_label != NULL)
10205 /* FIXME: calculation of value should be done while parsing */
10206 /* TODO: quadratic algorithm here. Change to an n log n one */
10207 long last_value = -1;
10208 const entity_t *entry = enumt->enume->base.next;
10209 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
10210 entry = entry->base.next) {
10211 const expression_t *expression = entry->enum_value.value;
10212 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
10213 bool found = false;
10214 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
10215 if (l->expression == NULL)
10217 if (l->first_case <= value && value <= l->last_case) {
10223 warningf(&statement->base.source_position,
10224 "enumeration value '%Y' not handled in switch",
10225 entry->base.symbol);
10227 last_value = value;
10232 * Parse a switch statement.
10234 static statement_t *parse_switch(void)
10236 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
10240 PUSH_PARENT(statement);
10242 expect('(', end_error);
10243 add_anchor_token(')');
10244 expression_t *const expr = parse_expression();
10245 mark_vars_read(expr, NULL);
10246 type_t * type = skip_typeref(expr->base.type);
10247 if (is_type_integer(type)) {
10248 type = promote_integer(type);
10249 if (warning.traditional) {
10250 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10251 warningf(&expr->base.source_position,
10252 "'%T' switch expression not converted to '%T' in ISO C",
10256 } else if (is_type_valid(type)) {
10257 errorf(&expr->base.source_position,
10258 "switch quantity is not an integer, but '%T'", type);
10259 type = type_error_type;
10261 statement->switchs.expression = create_implicit_cast(expr, type);
10262 expect(')', end_error);
10263 rem_anchor_token(')');
10265 switch_statement_t *rem = current_switch;
10266 current_switch = &statement->switchs;
10267 statement->switchs.body = parse_statement();
10268 current_switch = rem;
10270 if (warning.switch_default &&
10271 statement->switchs.default_label == NULL) {
10272 warningf(&statement->base.source_position, "switch has no default case");
10274 if (warning.switch_enum)
10275 check_enum_cases(&statement->switchs);
10281 return create_invalid_statement();
10284 static statement_t *parse_loop_body(statement_t *const loop)
10286 statement_t *const rem = current_loop;
10287 current_loop = loop;
10289 statement_t *const body = parse_statement();
10291 current_loop = rem;
10296 * Parse a while statement.
10298 static statement_t *parse_while(void)
10300 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10304 PUSH_PARENT(statement);
10306 expect('(', end_error);
10307 add_anchor_token(')');
10308 expression_t *const cond = parse_expression();
10309 statement->whiles.condition = cond;
10310 /* §6.8.5:2 The controlling expression of an iteration statement shall
10311 * have scalar type. */
10312 semantic_condition(cond, "condition of 'while'-statement");
10313 mark_vars_read(cond, NULL);
10314 rem_anchor_token(')');
10315 expect(')', end_error);
10317 statement->whiles.body = parse_loop_body(statement);
10323 return create_invalid_statement();
10327 * Parse a do statement.
10329 static statement_t *parse_do(void)
10331 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10335 PUSH_PARENT(statement);
10337 add_anchor_token(T_while);
10338 statement->do_while.body = parse_loop_body(statement);
10339 rem_anchor_token(T_while);
10341 expect(T_while, end_error);
10342 expect('(', end_error);
10343 add_anchor_token(')');
10344 expression_t *const cond = parse_expression();
10345 statement->do_while.condition = cond;
10346 /* §6.8.5:2 The controlling expression of an iteration statement shall
10347 * have scalar type. */
10348 semantic_condition(cond, "condition of 'do-while'-statement");
10349 mark_vars_read(cond, NULL);
10350 rem_anchor_token(')');
10351 expect(')', end_error);
10352 expect(';', end_error);
10358 return create_invalid_statement();
10362 * Parse a for statement.
10364 static statement_t *parse_for(void)
10366 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10370 expect('(', end_error1);
10371 add_anchor_token(')');
10373 PUSH_PARENT(statement);
10375 size_t const top = environment_top();
10376 scope_t *old_scope = scope_push(&statement->fors.scope);
10378 if (token.type == ';') {
10380 } else if (is_declaration_specifier(&token, false)) {
10381 parse_declaration(record_entity, DECL_FLAGS_NONE);
10383 add_anchor_token(';');
10384 expression_t *const init = parse_expression();
10385 statement->fors.initialisation = init;
10386 mark_vars_read(init, ENT_ANY);
10387 if (warning.unused_value && !expression_has_effect(init)) {
10388 warningf(&init->base.source_position,
10389 "initialisation of 'for'-statement has no effect");
10391 rem_anchor_token(';');
10392 expect(';', end_error2);
10395 if (token.type != ';') {
10396 add_anchor_token(';');
10397 expression_t *const cond = parse_expression();
10398 statement->fors.condition = cond;
10399 /* §6.8.5:2 The controlling expression of an iteration statement
10400 * shall have scalar type. */
10401 semantic_condition(cond, "condition of 'for'-statement");
10402 mark_vars_read(cond, NULL);
10403 rem_anchor_token(';');
10405 expect(';', end_error2);
10406 if (token.type != ')') {
10407 expression_t *const step = parse_expression();
10408 statement->fors.step = step;
10409 mark_vars_read(step, ENT_ANY);
10410 if (warning.unused_value && !expression_has_effect(step)) {
10411 warningf(&step->base.source_position,
10412 "step of 'for'-statement has no effect");
10415 expect(')', end_error2);
10416 rem_anchor_token(')');
10417 statement->fors.body = parse_loop_body(statement);
10419 assert(current_scope == &statement->fors.scope);
10420 scope_pop(old_scope);
10421 environment_pop_to(top);
10428 rem_anchor_token(')');
10429 assert(current_scope == &statement->fors.scope);
10430 scope_pop(old_scope);
10431 environment_pop_to(top);
10435 return create_invalid_statement();
10439 * Parse a goto statement.
10441 static statement_t *parse_goto(void)
10443 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10446 if (GNU_MODE && token.type == '*') {
10448 expression_t *expression = parse_expression();
10449 mark_vars_read(expression, NULL);
10451 /* Argh: although documentation says the expression must be of type void*,
10452 * gcc accepts anything that can be casted into void* without error */
10453 type_t *type = expression->base.type;
10455 if (type != type_error_type) {
10456 if (!is_type_pointer(type) && !is_type_integer(type)) {
10457 errorf(&expression->base.source_position,
10458 "cannot convert to a pointer type");
10459 } else if (warning.other && type != type_void_ptr) {
10460 warningf(&expression->base.source_position,
10461 "type of computed goto expression should be 'void*' not '%T'", type);
10463 expression = create_implicit_cast(expression, type_void_ptr);
10466 statement->gotos.expression = expression;
10468 if (token.type != T_IDENTIFIER) {
10470 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10472 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10473 eat_until_anchor();
10476 symbol_t *symbol = token.v.symbol;
10479 statement->gotos.label = get_label(symbol);
10482 /* remember the goto's in a list for later checking */
10483 *goto_anchor = &statement->gotos;
10484 goto_anchor = &statement->gotos.next;
10486 expect(';', end_error);
10490 return create_invalid_statement();
10494 * Parse a continue statement.
10496 static statement_t *parse_continue(void)
10498 if (current_loop == NULL) {
10499 errorf(HERE, "continue statement not within loop");
10502 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10505 expect(';', end_error);
10512 * Parse a break statement.
10514 static statement_t *parse_break(void)
10516 if (current_switch == NULL && current_loop == NULL) {
10517 errorf(HERE, "break statement not within loop or switch");
10520 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10523 expect(';', end_error);
10530 * Parse a __leave statement.
10532 static statement_t *parse_leave_statement(void)
10534 if (current_try == NULL) {
10535 errorf(HERE, "__leave statement not within __try");
10538 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10541 expect(';', end_error);
10548 * Check if a given entity represents a local variable.
10550 static bool is_local_variable(const entity_t *entity)
10552 if (entity->kind != ENTITY_VARIABLE)
10555 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10556 case STORAGE_CLASS_AUTO:
10557 case STORAGE_CLASS_REGISTER: {
10558 const type_t *type = skip_typeref(entity->declaration.type);
10559 if (is_type_function(type)) {
10571 * Check if a given expression represents a local variable.
10573 static bool expression_is_local_variable(const expression_t *expression)
10575 if (expression->base.kind != EXPR_REFERENCE) {
10578 const entity_t *entity = expression->reference.entity;
10579 return is_local_variable(entity);
10583 * Check if a given expression represents a local variable and
10584 * return its declaration then, else return NULL.
10586 entity_t *expression_is_variable(const expression_t *expression)
10588 if (expression->base.kind != EXPR_REFERENCE) {
10591 entity_t *entity = expression->reference.entity;
10592 if (entity->kind != ENTITY_VARIABLE)
10599 * Parse a return statement.
10601 static statement_t *parse_return(void)
10605 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10607 expression_t *return_value = NULL;
10608 if (token.type != ';') {
10609 return_value = parse_expression();
10610 mark_vars_read(return_value, NULL);
10613 const type_t *const func_type = skip_typeref(current_function->base.type);
10614 assert(is_type_function(func_type));
10615 type_t *const return_type = skip_typeref(func_type->function.return_type);
10617 source_position_t const *const pos = &statement->base.source_position;
10618 if (return_value != NULL) {
10619 type_t *return_value_type = skip_typeref(return_value->base.type);
10621 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10622 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10623 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10624 /* Only warn in C mode, because GCC does the same */
10625 if (c_mode & _CXX || strict_mode) {
10627 "'return' with a value, in function returning 'void'");
10628 } else if (warning.other) {
10630 "'return' with a value, in function returning 'void'");
10632 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10633 /* Only warn in C mode, because GCC does the same */
10636 "'return' with expression in function return 'void'");
10637 } else if (warning.other) {
10639 "'return' with expression in function return 'void'");
10643 assign_error_t error = semantic_assign(return_type, return_value);
10644 report_assign_error(error, return_type, return_value, "'return'",
10647 return_value = create_implicit_cast(return_value, return_type);
10648 /* check for returning address of a local var */
10649 if (warning.other && return_value != NULL
10650 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10651 const expression_t *expression = return_value->unary.value;
10652 if (expression_is_local_variable(expression)) {
10653 warningf(pos, "function returns address of local variable");
10656 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10657 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10658 if (c_mode & _CXX || strict_mode) {
10660 "'return' without value, in function returning non-void");
10663 "'return' without value, in function returning non-void");
10666 statement->returns.value = return_value;
10668 expect(';', end_error);
10675 * Parse a declaration statement.
10677 static statement_t *parse_declaration_statement(void)
10679 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10681 entity_t *before = current_scope->last_entity;
10683 parse_external_declaration();
10685 parse_declaration(record_entity, DECL_FLAGS_NONE);
10688 declaration_statement_t *const decl = &statement->declaration;
10689 entity_t *const begin =
10690 before != NULL ? before->base.next : current_scope->entities;
10691 decl->declarations_begin = begin;
10692 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10698 * Parse an expression statement, ie. expr ';'.
10700 static statement_t *parse_expression_statement(void)
10702 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10704 expression_t *const expr = parse_expression();
10705 statement->expression.expression = expr;
10706 mark_vars_read(expr, ENT_ANY);
10708 expect(';', end_error);
10715 * Parse a microsoft __try { } __finally { } or
10716 * __try{ } __except() { }
10718 static statement_t *parse_ms_try_statment(void)
10720 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10723 PUSH_PARENT(statement);
10725 ms_try_statement_t *rem = current_try;
10726 current_try = &statement->ms_try;
10727 statement->ms_try.try_statement = parse_compound_statement(false);
10732 if (token.type == T___except) {
10734 expect('(', end_error);
10735 add_anchor_token(')');
10736 expression_t *const expr = parse_expression();
10737 mark_vars_read(expr, NULL);
10738 type_t * type = skip_typeref(expr->base.type);
10739 if (is_type_integer(type)) {
10740 type = promote_integer(type);
10741 } else if (is_type_valid(type)) {
10742 errorf(&expr->base.source_position,
10743 "__expect expression is not an integer, but '%T'", type);
10744 type = type_error_type;
10746 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10747 rem_anchor_token(')');
10748 expect(')', end_error);
10749 statement->ms_try.final_statement = parse_compound_statement(false);
10750 } else if (token.type == T__finally) {
10752 statement->ms_try.final_statement = parse_compound_statement(false);
10754 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10755 return create_invalid_statement();
10759 return create_invalid_statement();
10762 static statement_t *parse_empty_statement(void)
10764 if (warning.empty_statement) {
10765 warningf(HERE, "statement is empty");
10767 statement_t *const statement = create_empty_statement();
10772 static statement_t *parse_local_label_declaration(void)
10774 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10778 entity_t *begin = NULL, *end = NULL;
10781 if (token.type != T_IDENTIFIER) {
10782 parse_error_expected("while parsing local label declaration",
10783 T_IDENTIFIER, NULL);
10786 symbol_t *symbol = token.v.symbol;
10787 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10788 if (entity != NULL && entity->base.parent_scope == current_scope) {
10789 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10790 symbol, &entity->base.source_position);
10792 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10794 entity->base.parent_scope = current_scope;
10795 entity->base.namespc = NAMESPACE_LABEL;
10796 entity->base.source_position = token.source_position;
10797 entity->base.symbol = symbol;
10800 end->base.next = entity;
10805 environment_push(entity);
10809 if (token.type != ',')
10815 statement->declaration.declarations_begin = begin;
10816 statement->declaration.declarations_end = end;
10820 static void parse_namespace_definition(void)
10824 entity_t *entity = NULL;
10825 symbol_t *symbol = NULL;
10827 if (token.type == T_IDENTIFIER) {
10828 symbol = token.v.symbol;
10831 entity = get_entity(symbol, NAMESPACE_NORMAL);
10832 if (entity != NULL &&
10833 entity->kind != ENTITY_NAMESPACE &&
10834 entity->base.parent_scope == current_scope) {
10835 if (!is_error_entity(entity)) {
10836 error_redefined_as_different_kind(&token.source_position,
10837 entity, ENTITY_NAMESPACE);
10843 if (entity == NULL) {
10844 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10845 entity->base.symbol = symbol;
10846 entity->base.source_position = token.source_position;
10847 entity->base.namespc = NAMESPACE_NORMAL;
10848 entity->base.parent_scope = current_scope;
10851 if (token.type == '=') {
10852 /* TODO: parse namespace alias */
10853 panic("namespace alias definition not supported yet");
10856 environment_push(entity);
10857 append_entity(current_scope, entity);
10859 size_t const top = environment_top();
10860 scope_t *old_scope = scope_push(&entity->namespacee.members);
10862 expect('{', end_error);
10864 expect('}', end_error);
10867 assert(current_scope == &entity->namespacee.members);
10868 scope_pop(old_scope);
10869 environment_pop_to(top);
10873 * Parse a statement.
10874 * There's also parse_statement() which additionally checks for
10875 * "statement has no effect" warnings
10877 static statement_t *intern_parse_statement(void)
10879 statement_t *statement = NULL;
10881 /* declaration or statement */
10882 add_anchor_token(';');
10883 switch (token.type) {
10884 case T_IDENTIFIER: {
10885 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10886 if (la1_type == ':') {
10887 statement = parse_label_statement();
10888 } else if (is_typedef_symbol(token.v.symbol)) {
10889 statement = parse_declaration_statement();
10891 /* it's an identifier, the grammar says this must be an
10892 * expression statement. However it is common that users mistype
10893 * declaration types, so we guess a bit here to improve robustness
10894 * for incorrect programs */
10895 switch (la1_type) {
10898 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10899 goto expression_statment;
10904 statement = parse_declaration_statement();
10908 expression_statment:
10909 statement = parse_expression_statement();
10916 case T___extension__:
10917 /* This can be a prefix to a declaration or an expression statement.
10918 * We simply eat it now and parse the rest with tail recursion. */
10921 } while (token.type == T___extension__);
10922 bool old_gcc_extension = in_gcc_extension;
10923 in_gcc_extension = true;
10924 statement = intern_parse_statement();
10925 in_gcc_extension = old_gcc_extension;
10929 statement = parse_declaration_statement();
10933 statement = parse_local_label_declaration();
10936 case ';': statement = parse_empty_statement(); break;
10937 case '{': statement = parse_compound_statement(false); break;
10938 case T___leave: statement = parse_leave_statement(); break;
10939 case T___try: statement = parse_ms_try_statment(); break;
10940 case T_asm: statement = parse_asm_statement(); break;
10941 case T_break: statement = parse_break(); break;
10942 case T_case: statement = parse_case_statement(); break;
10943 case T_continue: statement = parse_continue(); break;
10944 case T_default: statement = parse_default_statement(); break;
10945 case T_do: statement = parse_do(); break;
10946 case T_for: statement = parse_for(); break;
10947 case T_goto: statement = parse_goto(); break;
10948 case T_if: statement = parse_if(); break;
10949 case T_return: statement = parse_return(); break;
10950 case T_switch: statement = parse_switch(); break;
10951 case T_while: statement = parse_while(); break;
10954 statement = parse_expression_statement();
10958 errorf(HERE, "unexpected token %K while parsing statement", &token);
10959 statement = create_invalid_statement();
10964 rem_anchor_token(';');
10966 assert(statement != NULL
10967 && statement->base.source_position.input_name != NULL);
10973 * parse a statement and emits "statement has no effect" warning if needed
10974 * (This is really a wrapper around intern_parse_statement with check for 1
10975 * single warning. It is needed, because for statement expressions we have
10976 * to avoid the warning on the last statement)
10978 static statement_t *parse_statement(void)
10980 statement_t *statement = intern_parse_statement();
10982 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10983 expression_t *expression = statement->expression.expression;
10984 if (!expression_has_effect(expression)) {
10985 warningf(&expression->base.source_position,
10986 "statement has no effect");
10994 * Parse a compound statement.
10996 static statement_t *parse_compound_statement(bool inside_expression_statement)
10998 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
11000 PUSH_PARENT(statement);
11003 add_anchor_token('}');
11004 /* tokens, which can start a statement */
11005 /* TODO MS, __builtin_FOO */
11006 add_anchor_token('!');
11007 add_anchor_token('&');
11008 add_anchor_token('(');
11009 add_anchor_token('*');
11010 add_anchor_token('+');
11011 add_anchor_token('-');
11012 add_anchor_token('{');
11013 add_anchor_token('~');
11014 add_anchor_token(T_CHARACTER_CONSTANT);
11015 add_anchor_token(T_COLONCOLON);
11016 add_anchor_token(T_FLOATINGPOINT);
11017 add_anchor_token(T_IDENTIFIER);
11018 add_anchor_token(T_INTEGER);
11019 add_anchor_token(T_MINUSMINUS);
11020 add_anchor_token(T_PLUSPLUS);
11021 add_anchor_token(T_STRING_LITERAL);
11022 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11023 add_anchor_token(T_WIDE_STRING_LITERAL);
11024 add_anchor_token(T__Bool);
11025 add_anchor_token(T__Complex);
11026 add_anchor_token(T__Imaginary);
11027 add_anchor_token(T___FUNCTION__);
11028 add_anchor_token(T___PRETTY_FUNCTION__);
11029 add_anchor_token(T___alignof__);
11030 add_anchor_token(T___attribute__);
11031 add_anchor_token(T___builtin_va_start);
11032 add_anchor_token(T___extension__);
11033 add_anchor_token(T___func__);
11034 add_anchor_token(T___imag__);
11035 add_anchor_token(T___label__);
11036 add_anchor_token(T___real__);
11037 add_anchor_token(T___thread);
11038 add_anchor_token(T_asm);
11039 add_anchor_token(T_auto);
11040 add_anchor_token(T_bool);
11041 add_anchor_token(T_break);
11042 add_anchor_token(T_case);
11043 add_anchor_token(T_char);
11044 add_anchor_token(T_class);
11045 add_anchor_token(T_const);
11046 add_anchor_token(T_const_cast);
11047 add_anchor_token(T_continue);
11048 add_anchor_token(T_default);
11049 add_anchor_token(T_delete);
11050 add_anchor_token(T_double);
11051 add_anchor_token(T_do);
11052 add_anchor_token(T_dynamic_cast);
11053 add_anchor_token(T_enum);
11054 add_anchor_token(T_extern);
11055 add_anchor_token(T_false);
11056 add_anchor_token(T_float);
11057 add_anchor_token(T_for);
11058 add_anchor_token(T_goto);
11059 add_anchor_token(T_if);
11060 add_anchor_token(T_inline);
11061 add_anchor_token(T_int);
11062 add_anchor_token(T_long);
11063 add_anchor_token(T_new);
11064 add_anchor_token(T_operator);
11065 add_anchor_token(T_register);
11066 add_anchor_token(T_reinterpret_cast);
11067 add_anchor_token(T_restrict);
11068 add_anchor_token(T_return);
11069 add_anchor_token(T_short);
11070 add_anchor_token(T_signed);
11071 add_anchor_token(T_sizeof);
11072 add_anchor_token(T_static);
11073 add_anchor_token(T_static_cast);
11074 add_anchor_token(T_struct);
11075 add_anchor_token(T_switch);
11076 add_anchor_token(T_template);
11077 add_anchor_token(T_this);
11078 add_anchor_token(T_throw);
11079 add_anchor_token(T_true);
11080 add_anchor_token(T_try);
11081 add_anchor_token(T_typedef);
11082 add_anchor_token(T_typeid);
11083 add_anchor_token(T_typename);
11084 add_anchor_token(T_typeof);
11085 add_anchor_token(T_union);
11086 add_anchor_token(T_unsigned);
11087 add_anchor_token(T_using);
11088 add_anchor_token(T_void);
11089 add_anchor_token(T_volatile);
11090 add_anchor_token(T_wchar_t);
11091 add_anchor_token(T_while);
11093 size_t const top = environment_top();
11094 scope_t *old_scope = scope_push(&statement->compound.scope);
11096 statement_t **anchor = &statement->compound.statements;
11097 bool only_decls_so_far = true;
11098 while (token.type != '}') {
11099 if (token.type == T_EOF) {
11100 errorf(&statement->base.source_position,
11101 "EOF while parsing compound statement");
11104 statement_t *sub_statement = intern_parse_statement();
11105 if (is_invalid_statement(sub_statement)) {
11106 /* an error occurred. if we are at an anchor, return */
11112 if (warning.declaration_after_statement) {
11113 if (sub_statement->kind != STATEMENT_DECLARATION) {
11114 only_decls_so_far = false;
11115 } else if (!only_decls_so_far) {
11116 warningf(&sub_statement->base.source_position,
11117 "ISO C90 forbids mixed declarations and code");
11121 *anchor = sub_statement;
11123 while (sub_statement->base.next != NULL)
11124 sub_statement = sub_statement->base.next;
11126 anchor = &sub_statement->base.next;
11130 /* look over all statements again to produce no effect warnings */
11131 if (warning.unused_value) {
11132 statement_t *sub_statement = statement->compound.statements;
11133 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
11134 if (sub_statement->kind != STATEMENT_EXPRESSION)
11136 /* don't emit a warning for the last expression in an expression
11137 * statement as it has always an effect */
11138 if (inside_expression_statement && sub_statement->base.next == NULL)
11141 expression_t *expression = sub_statement->expression.expression;
11142 if (!expression_has_effect(expression)) {
11143 warningf(&expression->base.source_position,
11144 "statement has no effect");
11150 rem_anchor_token(T_while);
11151 rem_anchor_token(T_wchar_t);
11152 rem_anchor_token(T_volatile);
11153 rem_anchor_token(T_void);
11154 rem_anchor_token(T_using);
11155 rem_anchor_token(T_unsigned);
11156 rem_anchor_token(T_union);
11157 rem_anchor_token(T_typeof);
11158 rem_anchor_token(T_typename);
11159 rem_anchor_token(T_typeid);
11160 rem_anchor_token(T_typedef);
11161 rem_anchor_token(T_try);
11162 rem_anchor_token(T_true);
11163 rem_anchor_token(T_throw);
11164 rem_anchor_token(T_this);
11165 rem_anchor_token(T_template);
11166 rem_anchor_token(T_switch);
11167 rem_anchor_token(T_struct);
11168 rem_anchor_token(T_static_cast);
11169 rem_anchor_token(T_static);
11170 rem_anchor_token(T_sizeof);
11171 rem_anchor_token(T_signed);
11172 rem_anchor_token(T_short);
11173 rem_anchor_token(T_return);
11174 rem_anchor_token(T_restrict);
11175 rem_anchor_token(T_reinterpret_cast);
11176 rem_anchor_token(T_register);
11177 rem_anchor_token(T_operator);
11178 rem_anchor_token(T_new);
11179 rem_anchor_token(T_long);
11180 rem_anchor_token(T_int);
11181 rem_anchor_token(T_inline);
11182 rem_anchor_token(T_if);
11183 rem_anchor_token(T_goto);
11184 rem_anchor_token(T_for);
11185 rem_anchor_token(T_float);
11186 rem_anchor_token(T_false);
11187 rem_anchor_token(T_extern);
11188 rem_anchor_token(T_enum);
11189 rem_anchor_token(T_dynamic_cast);
11190 rem_anchor_token(T_do);
11191 rem_anchor_token(T_double);
11192 rem_anchor_token(T_delete);
11193 rem_anchor_token(T_default);
11194 rem_anchor_token(T_continue);
11195 rem_anchor_token(T_const_cast);
11196 rem_anchor_token(T_const);
11197 rem_anchor_token(T_class);
11198 rem_anchor_token(T_char);
11199 rem_anchor_token(T_case);
11200 rem_anchor_token(T_break);
11201 rem_anchor_token(T_bool);
11202 rem_anchor_token(T_auto);
11203 rem_anchor_token(T_asm);
11204 rem_anchor_token(T___thread);
11205 rem_anchor_token(T___real__);
11206 rem_anchor_token(T___label__);
11207 rem_anchor_token(T___imag__);
11208 rem_anchor_token(T___func__);
11209 rem_anchor_token(T___extension__);
11210 rem_anchor_token(T___builtin_va_start);
11211 rem_anchor_token(T___attribute__);
11212 rem_anchor_token(T___alignof__);
11213 rem_anchor_token(T___PRETTY_FUNCTION__);
11214 rem_anchor_token(T___FUNCTION__);
11215 rem_anchor_token(T__Imaginary);
11216 rem_anchor_token(T__Complex);
11217 rem_anchor_token(T__Bool);
11218 rem_anchor_token(T_WIDE_STRING_LITERAL);
11219 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
11220 rem_anchor_token(T_STRING_LITERAL);
11221 rem_anchor_token(T_PLUSPLUS);
11222 rem_anchor_token(T_MINUSMINUS);
11223 rem_anchor_token(T_INTEGER);
11224 rem_anchor_token(T_IDENTIFIER);
11225 rem_anchor_token(T_FLOATINGPOINT);
11226 rem_anchor_token(T_COLONCOLON);
11227 rem_anchor_token(T_CHARACTER_CONSTANT);
11228 rem_anchor_token('~');
11229 rem_anchor_token('{');
11230 rem_anchor_token('-');
11231 rem_anchor_token('+');
11232 rem_anchor_token('*');
11233 rem_anchor_token('(');
11234 rem_anchor_token('&');
11235 rem_anchor_token('!');
11236 rem_anchor_token('}');
11237 assert(current_scope == &statement->compound.scope);
11238 scope_pop(old_scope);
11239 environment_pop_to(top);
11246 * Check for unused global static functions and variables
11248 static void check_unused_globals(void)
11250 if (!warning.unused_function && !warning.unused_variable)
11253 for (const entity_t *entity = file_scope->entities; entity != NULL;
11254 entity = entity->base.next) {
11255 if (!is_declaration(entity))
11258 const declaration_t *declaration = &entity->declaration;
11259 if (declaration->used ||
11260 declaration->modifiers & DM_UNUSED ||
11261 declaration->modifiers & DM_USED ||
11262 declaration->storage_class != STORAGE_CLASS_STATIC)
11265 type_t *const type = declaration->type;
11267 if (entity->kind == ENTITY_FUNCTION) {
11268 /* inhibit warning for static inline functions */
11269 if (entity->function.is_inline)
11272 s = entity->function.statement != NULL ? "defined" : "declared";
11277 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11278 type, declaration->base.symbol, s);
11282 static void parse_global_asm(void)
11284 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11287 expect('(', end_error);
11289 statement->asms.asm_text = parse_string_literals();
11290 statement->base.next = unit->global_asm;
11291 unit->global_asm = statement;
11293 expect(')', end_error);
11294 expect(';', end_error);
11299 static void parse_linkage_specification(void)
11302 assert(token.type == T_STRING_LITERAL);
11304 const char *linkage = parse_string_literals().begin;
11306 linkage_kind_t old_linkage = current_linkage;
11307 linkage_kind_t new_linkage;
11308 if (strcmp(linkage, "C") == 0) {
11309 new_linkage = LINKAGE_C;
11310 } else if (strcmp(linkage, "C++") == 0) {
11311 new_linkage = LINKAGE_CXX;
11313 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11314 new_linkage = LINKAGE_INVALID;
11316 current_linkage = new_linkage;
11318 if (token.type == '{') {
11321 expect('}', end_error);
11327 assert(current_linkage == new_linkage);
11328 current_linkage = old_linkage;
11331 static void parse_external(void)
11333 switch (token.type) {
11334 DECLARATION_START_NO_EXTERN
11336 case T___extension__:
11337 /* tokens below are for implicit int */
11338 case '&': /* & x; -> int& x; (and error later, because C++ has no
11340 case '*': /* * x; -> int* x; */
11341 case '(': /* (x); -> int (x); */
11342 parse_external_declaration();
11346 if (look_ahead(1)->type == T_STRING_LITERAL) {
11347 parse_linkage_specification();
11349 parse_external_declaration();
11354 parse_global_asm();
11358 parse_namespace_definition();
11362 if (!strict_mode) {
11364 warningf(HERE, "stray ';' outside of function");
11371 errorf(HERE, "stray %K outside of function", &token);
11372 if (token.type == '(' || token.type == '{' || token.type == '[')
11373 eat_until_matching_token(token.type);
11379 static void parse_externals(void)
11381 add_anchor_token('}');
11382 add_anchor_token(T_EOF);
11385 unsigned char token_anchor_copy[T_LAST_TOKEN];
11386 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11389 while (token.type != T_EOF && token.type != '}') {
11391 bool anchor_leak = false;
11392 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11393 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11395 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11396 anchor_leak = true;
11399 if (in_gcc_extension) {
11400 errorf(HERE, "Leaked __extension__");
11401 anchor_leak = true;
11411 rem_anchor_token(T_EOF);
11412 rem_anchor_token('}');
11416 * Parse a translation unit.
11418 static void parse_translation_unit(void)
11420 add_anchor_token(T_EOF);
11425 if (token.type == T_EOF)
11428 errorf(HERE, "stray %K outside of function", &token);
11429 if (token.type == '(' || token.type == '{' || token.type == '[')
11430 eat_until_matching_token(token.type);
11438 * @return the translation unit or NULL if errors occurred.
11440 void start_parsing(void)
11442 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11443 label_stack = NEW_ARR_F(stack_entry_t, 0);
11444 diagnostic_count = 0;
11448 type_set_output(stderr);
11449 ast_set_output(stderr);
11451 assert(unit == NULL);
11452 unit = allocate_ast_zero(sizeof(unit[0]));
11454 assert(file_scope == NULL);
11455 file_scope = &unit->scope;
11457 assert(current_scope == NULL);
11458 scope_push(&unit->scope);
11461 translation_unit_t *finish_parsing(void)
11463 assert(current_scope == &unit->scope);
11466 assert(file_scope == &unit->scope);
11467 check_unused_globals();
11470 DEL_ARR_F(environment_stack);
11471 DEL_ARR_F(label_stack);
11473 translation_unit_t *result = unit;
11478 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
11479 * are given length one. */
11480 static void complete_incomplete_arrays(void)
11482 size_t n = ARR_LEN(incomplete_arrays);
11483 for (size_t i = 0; i != n; ++i) {
11484 declaration_t *const decl = incomplete_arrays[i];
11485 type_t *const orig_type = decl->type;
11486 type_t *const type = skip_typeref(orig_type);
11488 if (!is_type_incomplete(type))
11491 if (warning.other) {
11492 warningf(&decl->base.source_position,
11493 "array '%#T' assumed to have one element",
11494 orig_type, decl->base.symbol);
11497 type_t *const new_type = duplicate_type(type);
11498 new_type->array.size_constant = true;
11499 new_type->array.has_implicit_size = true;
11500 new_type->array.size = 1;
11502 type_t *const result = identify_new_type(new_type);
11504 decl->type = result;
11510 lookahead_bufpos = 0;
11511 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11514 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11515 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11516 parse_translation_unit();
11517 complete_incomplete_arrays();
11518 DEL_ARR_F(incomplete_arrays);
11519 incomplete_arrays = NULL;
11523 * Initialize the parser.
11525 void init_parser(void)
11527 sym_anonymous = symbol_table_insert("<anonymous>");
11529 if (c_mode & _MS) {
11530 /* add predefined symbols for extended-decl-modifier */
11531 sym_align = symbol_table_insert("align");
11532 sym_allocate = symbol_table_insert("allocate");
11533 sym_dllimport = symbol_table_insert("dllimport");
11534 sym_dllexport = symbol_table_insert("dllexport");
11535 sym_naked = symbol_table_insert("naked");
11536 sym_noinline = symbol_table_insert("noinline");
11537 sym_returns_twice = symbol_table_insert("returns_twice");
11538 sym_noreturn = symbol_table_insert("noreturn");
11539 sym_nothrow = symbol_table_insert("nothrow");
11540 sym_novtable = symbol_table_insert("novtable");
11541 sym_property = symbol_table_insert("property");
11542 sym_get = symbol_table_insert("get");
11543 sym_put = symbol_table_insert("put");
11544 sym_selectany = symbol_table_insert("selectany");
11545 sym_thread = symbol_table_insert("thread");
11546 sym_uuid = symbol_table_insert("uuid");
11547 sym_deprecated = symbol_table_insert("deprecated");
11548 sym_restrict = symbol_table_insert("restrict");
11549 sym_noalias = symbol_table_insert("noalias");
11551 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11553 init_expression_parsers();
11554 obstack_init(&temp_obst);
11556 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11557 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11561 * Terminate the parser.
11563 void exit_parser(void)
11565 obstack_free(&temp_obst, NULL);