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 2
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 have_arguments; /**< True, if this attribute has arguments. */
68 atomic_type_kind_t akind;
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 int 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_noreturn = NULL;
160 static const symbol_t *sym_nothrow = NULL;
161 static const symbol_t *sym_novtable = NULL;
162 static const symbol_t *sym_property = NULL;
163 static const symbol_t *sym_get = NULL;
164 static const symbol_t *sym_put = NULL;
165 static const symbol_t *sym_selectany = NULL;
166 static const symbol_t *sym_thread = NULL;
167 static const symbol_t *sym_uuid = NULL;
168 static const symbol_t *sym_deprecated = NULL;
169 static const symbol_t *sym_restrict = NULL;
170 static const symbol_t *sym_noalias = NULL;
172 /** The token anchor set */
173 static unsigned char token_anchor_set[T_LAST_TOKEN];
175 /** The current source position. */
176 #define HERE (&token.source_position)
178 /** true if we are in GCC mode. */
179 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
181 static type_t *type_valist;
183 static statement_t *parse_compound_statement(bool inside_expression_statement);
184 static statement_t *parse_statement(void);
186 static expression_t *parse_sub_expression(precedence_t);
187 static expression_t *parse_expression(void);
188 static type_t *parse_typename(void);
189 static void parse_externals(void);
190 static void parse_external(void);
192 static void parse_compound_type_entries(compound_t *compound_declaration);
194 typedef enum declarator_flags_t {
196 DECL_MAY_BE_ABSTRACT = 1U << 0,
197 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
198 DECL_IS_PARAMETER = 1U << 2
199 } declarator_flags_t;
201 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
202 declarator_flags_t flags);
204 static entity_t *record_entity(entity_t *entity, bool is_definition);
206 static void semantic_comparison(binary_expression_t *expression);
208 #define STORAGE_CLASSES \
209 STORAGE_CLASSES_NO_EXTERN \
212 #define STORAGE_CLASSES_NO_EXTERN \
219 #define TYPE_QUALIFIERS \
224 case T__forceinline: \
225 case T___attribute__:
227 #define COMPLEX_SPECIFIERS \
229 #define IMAGINARY_SPECIFIERS \
232 #define TYPE_SPECIFIERS \
234 case T___builtin_va_list: \
253 #define DECLARATION_START \
258 #define DECLARATION_START_NO_EXTERN \
259 STORAGE_CLASSES_NO_EXTERN \
263 #define TYPENAME_START \
267 #define EXPRESSION_START \
276 case T_CHARACTER_CONSTANT: \
277 case T_FLOATINGPOINT: \
281 case T_STRING_LITERAL: \
282 case T_WIDE_CHARACTER_CONSTANT: \
283 case T_WIDE_STRING_LITERAL: \
284 case T___FUNCDNAME__: \
285 case T___FUNCSIG__: \
286 case T___FUNCTION__: \
287 case T___PRETTY_FUNCTION__: \
288 case T___alignof__: \
289 case T___builtin_alloca: \
290 case T___builtin_classify_type: \
291 case T___builtin_constant_p: \
292 case T___builtin_expect: \
293 case T___builtin_huge_val: \
294 case T___builtin_inf: \
295 case T___builtin_inff: \
296 case T___builtin_infl: \
297 case T___builtin_isgreater: \
298 case T___builtin_isgreaterequal: \
299 case T___builtin_isless: \
300 case T___builtin_islessequal: \
301 case T___builtin_islessgreater: \
302 case T___builtin_isunordered: \
303 case T___builtin_nan: \
304 case T___builtin_nanf: \
305 case T___builtin_nanl: \
306 case T___builtin_offsetof: \
307 case T___builtin_prefetch: \
308 case T___builtin_va_arg: \
309 case T___builtin_va_end: \
310 case T___builtin_va_start: \
321 * Allocate an AST node with given size and
322 * initialize all fields with zero.
324 static void *allocate_ast_zero(size_t size)
326 void *res = allocate_ast(size);
327 memset(res, 0, size);
332 * Returns the size of an entity node.
334 * @param kind the entity kind
336 static size_t get_entity_struct_size(entity_kind_t kind)
338 static const size_t sizes[] = {
339 [ENTITY_VARIABLE] = sizeof(variable_t),
340 [ENTITY_PARAMETER] = sizeof(parameter_t),
341 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
342 [ENTITY_FUNCTION] = sizeof(function_t),
343 [ENTITY_TYPEDEF] = sizeof(typedef_t),
344 [ENTITY_STRUCT] = sizeof(compound_t),
345 [ENTITY_UNION] = sizeof(compound_t),
346 [ENTITY_ENUM] = sizeof(enum_t),
347 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
348 [ENTITY_LABEL] = sizeof(label_t),
349 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
350 [ENTITY_NAMESPACE] = sizeof(namespace_t)
352 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
353 assert(sizes[kind] != 0);
358 * Allocate an entity of given kind and initialize all
361 static entity_t *allocate_entity_zero(entity_kind_t kind)
363 size_t size = get_entity_struct_size(kind);
364 entity_t *entity = allocate_ast_zero(size);
370 * Returns the size of a statement node.
372 * @param kind the statement kind
374 static size_t get_statement_struct_size(statement_kind_t kind)
376 static const size_t sizes[] = {
377 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
378 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
379 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
380 [STATEMENT_RETURN] = sizeof(return_statement_t),
381 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
382 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
383 [STATEMENT_IF] = sizeof(if_statement_t),
384 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
385 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
386 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
387 [STATEMENT_BREAK] = sizeof(statement_base_t),
388 [STATEMENT_GOTO] = sizeof(goto_statement_t),
389 [STATEMENT_LABEL] = sizeof(label_statement_t),
390 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
391 [STATEMENT_WHILE] = sizeof(while_statement_t),
392 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
393 [STATEMENT_FOR] = sizeof(for_statement_t),
394 [STATEMENT_ASM] = sizeof(asm_statement_t),
395 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
396 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
398 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
399 assert(sizes[kind] != 0);
404 * Returns the size of an expression node.
406 * @param kind the expression kind
408 static size_t get_expression_struct_size(expression_kind_t kind)
410 static const size_t sizes[] = {
411 [EXPR_INVALID] = sizeof(expression_base_t),
412 [EXPR_REFERENCE] = sizeof(reference_expression_t),
413 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
414 [EXPR_CONST] = sizeof(const_expression_t),
415 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
416 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
417 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
418 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
419 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
420 [EXPR_CALL] = sizeof(call_expression_t),
421 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
422 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
423 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
424 [EXPR_SELECT] = sizeof(select_expression_t),
425 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
426 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
427 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
428 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
429 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
430 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
431 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
432 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
433 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
434 [EXPR_VA_START] = sizeof(va_start_expression_t),
435 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
436 [EXPR_STATEMENT] = sizeof(statement_expression_t),
437 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
439 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
440 return sizes[EXPR_UNARY_FIRST];
442 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
443 return sizes[EXPR_BINARY_FIRST];
445 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
446 assert(sizes[kind] != 0);
451 * Allocate a statement node of given kind and initialize all
452 * fields with zero. Sets its source position to the position
453 * of the current token.
455 static statement_t *allocate_statement_zero(statement_kind_t kind)
457 size_t size = get_statement_struct_size(kind);
458 statement_t *res = allocate_ast_zero(size);
460 res->base.kind = kind;
461 res->base.parent = current_parent;
462 res->base.source_position = token.source_position;
467 * Allocate an expression node of given kind and initialize all
470 static expression_t *allocate_expression_zero(expression_kind_t kind)
472 size_t size = get_expression_struct_size(kind);
473 expression_t *res = allocate_ast_zero(size);
475 res->base.kind = kind;
476 res->base.type = type_error_type;
477 res->base.source_position = token.source_position;
482 * Creates a new invalid expression at the source position
483 * of the current token.
485 static expression_t *create_invalid_expression(void)
487 return allocate_expression_zero(EXPR_INVALID);
491 * Creates a new invalid statement.
493 static statement_t *create_invalid_statement(void)
495 return allocate_statement_zero(STATEMENT_INVALID);
499 * Allocate a new empty statement.
501 static statement_t *create_empty_statement(void)
503 return allocate_statement_zero(STATEMENT_EMPTY);
507 * Returns the size of a type node.
509 * @param kind the type kind
511 static size_t get_type_struct_size(type_kind_t kind)
513 static const size_t sizes[] = {
514 [TYPE_ATOMIC] = sizeof(atomic_type_t),
515 [TYPE_COMPLEX] = sizeof(complex_type_t),
516 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
517 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
518 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
519 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
520 [TYPE_ENUM] = sizeof(enum_type_t),
521 [TYPE_FUNCTION] = sizeof(function_type_t),
522 [TYPE_POINTER] = sizeof(pointer_type_t),
523 [TYPE_ARRAY] = sizeof(array_type_t),
524 [TYPE_BUILTIN] = sizeof(builtin_type_t),
525 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
526 [TYPE_TYPEOF] = sizeof(typeof_type_t),
528 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
529 assert(kind <= TYPE_TYPEOF);
530 assert(sizes[kind] != 0);
535 * Allocate a type node of given kind and initialize all
538 * @param kind type kind to allocate
540 static type_t *allocate_type_zero(type_kind_t kind)
542 size_t size = get_type_struct_size(kind);
543 type_t *res = obstack_alloc(type_obst, size);
544 memset(res, 0, size);
545 res->base.kind = kind;
551 * Returns the size of an initializer node.
553 * @param kind the initializer kind
555 static size_t get_initializer_size(initializer_kind_t kind)
557 static const size_t sizes[] = {
558 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
559 [INITIALIZER_STRING] = sizeof(initializer_string_t),
560 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
561 [INITIALIZER_LIST] = sizeof(initializer_list_t),
562 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
564 assert(kind < sizeof(sizes) / sizeof(*sizes));
565 assert(sizes[kind] != 0);
570 * Allocate an initializer node of given kind and initialize all
573 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
575 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
582 * Free a type from the type obstack.
584 static void free_type(void *type)
586 obstack_free(type_obst, type);
590 * Returns the index of the top element of the environment stack.
592 static size_t environment_top(void)
594 return ARR_LEN(environment_stack);
598 * Returns the index of the top element of the global label stack.
600 static size_t label_top(void)
602 return ARR_LEN(label_stack);
606 * Return the next token.
608 static inline void next_token(void)
610 token = lookahead_buffer[lookahead_bufpos];
611 lookahead_buffer[lookahead_bufpos] = lexer_token;
614 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
617 print_token(stderr, &token);
618 fprintf(stderr, "\n");
623 * Return the next token with a given lookahead.
625 static inline const token_t *look_ahead(int num)
627 assert(num > 0 && num <= MAX_LOOKAHEAD);
628 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
629 return &lookahead_buffer[pos];
633 * Adds a token type to the token type anchor set (a multi-set).
635 static void add_anchor_token(int token_type)
637 assert(0 <= token_type && token_type < T_LAST_TOKEN);
638 ++token_anchor_set[token_type];
642 * Set the number of tokens types of the given type
643 * to zero and return the old count.
645 static int save_and_reset_anchor_state(int token_type)
647 assert(0 <= token_type && token_type < T_LAST_TOKEN);
648 int count = token_anchor_set[token_type];
649 token_anchor_set[token_type] = 0;
654 * Restore the number of token types to the given count.
656 static void restore_anchor_state(int token_type, int count)
658 assert(0 <= token_type && token_type < T_LAST_TOKEN);
659 token_anchor_set[token_type] = count;
663 * Remove a token type from the token type anchor set (a multi-set).
665 static void rem_anchor_token(int token_type)
667 assert(0 <= token_type && token_type < T_LAST_TOKEN);
668 assert(token_anchor_set[token_type] != 0);
669 --token_anchor_set[token_type];
673 * Return true if the token type of the current token is
676 static bool at_anchor(void)
680 return token_anchor_set[token.type];
684 * Eat tokens until a matching token type is found.
686 static void eat_until_matching_token(int type)
690 case '(': end_token = ')'; break;
691 case '{': end_token = '}'; break;
692 case '[': end_token = ']'; break;
693 default: end_token = type; break;
696 unsigned parenthesis_count = 0;
697 unsigned brace_count = 0;
698 unsigned bracket_count = 0;
699 while (token.type != end_token ||
700 parenthesis_count != 0 ||
702 bracket_count != 0) {
703 switch (token.type) {
705 case '(': ++parenthesis_count; break;
706 case '{': ++brace_count; break;
707 case '[': ++bracket_count; break;
710 if (parenthesis_count > 0)
720 if (bracket_count > 0)
723 if (token.type == end_token &&
724 parenthesis_count == 0 &&
738 * Eat input tokens until an anchor is found.
740 static void eat_until_anchor(void)
742 while (token_anchor_set[token.type] == 0) {
743 if (token.type == '(' || token.type == '{' || token.type == '[')
744 eat_until_matching_token(token.type);
750 * Eat a whole block from input tokens.
752 static void eat_block(void)
754 eat_until_matching_token('{');
755 if (token.type == '}')
759 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
762 * Report a parse error because an expected token was not found.
765 #if defined __GNUC__ && __GNUC__ >= 4
766 __attribute__((sentinel))
768 void parse_error_expected(const char *message, ...)
770 if (message != NULL) {
771 errorf(HERE, "%s", message);
774 va_start(ap, message);
775 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
780 * Report an incompatible type.
782 static void type_error_incompatible(const char *msg,
783 const source_position_t *source_position, type_t *type1, type_t *type2)
785 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
790 * Expect the current token is the expected token.
791 * If not, generate an error, eat the current statement,
792 * and goto the end_error label.
794 #define expect(expected) \
796 if (UNLIKELY(token.type != (expected))) { \
797 parse_error_expected(NULL, (expected), NULL); \
798 add_anchor_token(expected); \
799 eat_until_anchor(); \
800 if (token.type == expected) \
802 rem_anchor_token(expected); \
809 * Push a given scope on the scope stack and make it the
812 static scope_t *scope_push(scope_t *new_scope)
814 if (current_scope != NULL) {
815 new_scope->depth = current_scope->depth + 1;
818 scope_t *old_scope = current_scope;
819 current_scope = new_scope;
824 * Pop the current scope from the scope stack.
826 static void scope_pop(scope_t *old_scope)
828 current_scope = old_scope;
832 * Search an entity by its symbol in a given namespace.
834 static entity_t *get_entity(const symbol_t *const symbol,
835 namespace_tag_t namespc)
837 entity_t *entity = symbol->entity;
838 for (; entity != NULL; entity = entity->base.symbol_next) {
839 if (entity->base.namespc == namespc)
847 * pushs an entity on the environment stack and links the corresponding symbol
850 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
852 symbol_t *symbol = entity->base.symbol;
853 entity_namespace_t namespc = entity->base.namespc;
854 assert(namespc != NAMESPACE_INVALID);
856 /* replace/add entity into entity list of the symbol */
859 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
864 /* replace an entry? */
865 if (iter->base.namespc == namespc) {
866 entity->base.symbol_next = iter->base.symbol_next;
872 /* remember old declaration */
874 entry.symbol = symbol;
875 entry.old_entity = iter;
876 entry.namespc = namespc;
877 ARR_APP1(stack_entry_t, *stack_ptr, entry);
881 * Push an entity on the environment stack.
883 static void environment_push(entity_t *entity)
885 assert(entity->base.source_position.input_name != NULL);
886 assert(entity->base.parent_scope != NULL);
887 stack_push(&environment_stack, entity);
891 * Push a declaration on the global label stack.
893 * @param declaration the declaration
895 static void label_push(entity_t *label)
897 /* we abuse the parameters scope as parent for the labels */
898 label->base.parent_scope = ¤t_function->parameters;
899 stack_push(&label_stack, label);
903 * pops symbols from the environment stack until @p new_top is the top element
905 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
907 stack_entry_t *stack = *stack_ptr;
908 size_t top = ARR_LEN(stack);
911 assert(new_top <= top);
915 for (i = top; i > new_top; --i) {
916 stack_entry_t *entry = &stack[i - 1];
918 entity_t *old_entity = entry->old_entity;
919 symbol_t *symbol = entry->symbol;
920 entity_namespace_t namespc = entry->namespc;
922 /* replace with old_entity/remove */
925 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
927 assert(iter != NULL);
928 /* replace an entry? */
929 if (iter->base.namespc == namespc)
933 /* restore definition from outer scopes (if there was one) */
934 if (old_entity != NULL) {
935 old_entity->base.symbol_next = iter->base.symbol_next;
936 *anchor = old_entity;
938 /* remove entry from list */
939 *anchor = iter->base.symbol_next;
943 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
947 * Pop all entries from the environment stack until the new_top
950 * @param new_top the new stack top
952 static void environment_pop_to(size_t new_top)
954 stack_pop_to(&environment_stack, new_top);
958 * Pop all entries from the global label stack until the new_top
961 * @param new_top the new stack top
963 static void label_pop_to(size_t new_top)
965 stack_pop_to(&label_stack, new_top);
968 static int get_akind_rank(atomic_type_kind_t akind)
974 * Return the type rank for an atomic type.
976 static int get_rank(const type_t *type)
978 assert(!is_typeref(type));
979 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
980 * and esp. footnote 108). However we can't fold constants (yet), so we
981 * can't decide whether unsigned int is possible, while int always works.
982 * (unsigned int would be preferable when possible... for stuff like
983 * struct { enum { ... } bla : 4; } ) */
984 if (type->kind == TYPE_ENUM)
985 return get_akind_rank(ATOMIC_TYPE_INT);
987 assert(type->kind == TYPE_ATOMIC);
988 return get_akind_rank(type->atomic.akind);
992 * Do integer promotion for a given type.
994 * @param type the type to promote
995 * @return the promoted type
997 static type_t *promote_integer(type_t *type)
999 if (type->kind == TYPE_BITFIELD)
1000 type = type->bitfield.base_type;
1002 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
1009 * Create a cast expression.
1011 * @param expression the expression to cast
1012 * @param dest_type the destination type
1014 static expression_t *create_cast_expression(expression_t *expression,
1017 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
1019 cast->unary.value = expression;
1020 cast->base.type = dest_type;
1026 * Check if a given expression represents a null pointer constant.
1028 * @param expression the expression to check
1030 static bool is_null_pointer_constant(const expression_t *expression)
1032 /* skip void* cast */
1033 if (expression->kind == EXPR_UNARY_CAST
1034 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1035 expression = expression->unary.value;
1038 /* TODO: not correct yet, should be any constant integer expression
1039 * which evaluates to 0 */
1040 if (expression->kind != EXPR_CONST)
1043 type_t *const type = skip_typeref(expression->base.type);
1044 if (!is_type_integer(type))
1047 return expression->conste.v.int_value == 0;
1051 * Create an implicit cast expression.
1053 * @param expression the expression to cast
1054 * @param dest_type the destination type
1056 static expression_t *create_implicit_cast(expression_t *expression,
1059 type_t *const source_type = expression->base.type;
1061 if (source_type == dest_type)
1064 return create_cast_expression(expression, dest_type);
1067 typedef enum assign_error_t {
1069 ASSIGN_ERROR_INCOMPATIBLE,
1070 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1071 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1072 ASSIGN_WARNING_POINTER_FROM_INT,
1073 ASSIGN_WARNING_INT_FROM_POINTER
1076 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1077 const expression_t *const right,
1078 const char *context,
1079 const source_position_t *source_position)
1081 type_t *const orig_type_right = right->base.type;
1082 type_t *const type_left = skip_typeref(orig_type_left);
1083 type_t *const type_right = skip_typeref(orig_type_right);
1086 case ASSIGN_SUCCESS:
1088 case ASSIGN_ERROR_INCOMPATIBLE:
1089 errorf(source_position,
1090 "destination type '%T' in %s is incompatible with type '%T'",
1091 orig_type_left, context, orig_type_right);
1094 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1095 if (warning.other) {
1096 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1097 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1099 /* the left type has all qualifiers from the right type */
1100 unsigned missing_qualifiers
1101 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1102 warningf(source_position,
1103 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1104 orig_type_left, context, orig_type_right, missing_qualifiers);
1109 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1110 if (warning.other) {
1111 warningf(source_position,
1112 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1113 orig_type_left, context, right, orig_type_right);
1117 case ASSIGN_WARNING_POINTER_FROM_INT:
1118 if (warning.other) {
1119 warningf(source_position,
1120 "%s makes pointer '%T' from integer '%T' without a cast",
1121 context, orig_type_left, orig_type_right);
1125 case ASSIGN_WARNING_INT_FROM_POINTER:
1126 if (warning.other) {
1127 warningf(source_position,
1128 "%s makes integer '%T' from pointer '%T' without a cast",
1129 context, orig_type_left, orig_type_right);
1134 panic("invalid error value");
1138 /** Implements the rules from § 6.5.16.1 */
1139 static assign_error_t semantic_assign(type_t *orig_type_left,
1140 const expression_t *const right)
1142 type_t *const orig_type_right = right->base.type;
1143 type_t *const type_left = skip_typeref(orig_type_left);
1144 type_t *const type_right = skip_typeref(orig_type_right);
1146 if (is_type_pointer(type_left)) {
1147 if (is_null_pointer_constant(right)) {
1148 return ASSIGN_SUCCESS;
1149 } else if (is_type_pointer(type_right)) {
1150 type_t *points_to_left
1151 = skip_typeref(type_left->pointer.points_to);
1152 type_t *points_to_right
1153 = skip_typeref(type_right->pointer.points_to);
1154 assign_error_t res = ASSIGN_SUCCESS;
1156 /* the left type has all qualifiers from the right type */
1157 unsigned missing_qualifiers
1158 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1159 if (missing_qualifiers != 0) {
1160 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1163 points_to_left = get_unqualified_type(points_to_left);
1164 points_to_right = get_unqualified_type(points_to_right);
1166 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1169 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1170 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1171 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1174 if (!types_compatible(points_to_left, points_to_right)) {
1175 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1179 } else if (is_type_integer(type_right)) {
1180 return ASSIGN_WARNING_POINTER_FROM_INT;
1182 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1183 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1184 && is_type_pointer(type_right))) {
1185 return ASSIGN_SUCCESS;
1186 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1187 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1188 type_t *const unqual_type_left = get_unqualified_type(type_left);
1189 type_t *const unqual_type_right = get_unqualified_type(type_right);
1190 if (types_compatible(unqual_type_left, unqual_type_right)) {
1191 return ASSIGN_SUCCESS;
1193 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1194 return ASSIGN_WARNING_INT_FROM_POINTER;
1197 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1198 return ASSIGN_SUCCESS;
1200 return ASSIGN_ERROR_INCOMPATIBLE;
1203 static expression_t *parse_constant_expression(void)
1205 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1207 if (!is_constant_expression(result)) {
1208 errorf(&result->base.source_position,
1209 "expression '%E' is not constant", result);
1215 static expression_t *parse_assignment_expression(void)
1217 return parse_sub_expression(PREC_ASSIGNMENT);
1220 static string_t parse_string_literals(void)
1222 assert(token.type == T_STRING_LITERAL);
1223 string_t result = token.v.string;
1227 while (token.type == T_STRING_LITERAL) {
1228 result = concat_strings(&result, &token.v.string);
1235 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1236 [GNU_AK_CONST] = "const",
1237 [GNU_AK_VOLATILE] = "volatile",
1238 [GNU_AK_CDECL] = "cdecl",
1239 [GNU_AK_STDCALL] = "stdcall",
1240 [GNU_AK_FASTCALL] = "fastcall",
1241 [GNU_AK_DEPRECATED] = "deprecated",
1242 [GNU_AK_NOINLINE] = "noinline",
1243 [GNU_AK_NORETURN] = "noreturn",
1244 [GNU_AK_NAKED] = "naked",
1245 [GNU_AK_PURE] = "pure",
1246 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1247 [GNU_AK_MALLOC] = "malloc",
1248 [GNU_AK_WEAK] = "weak",
1249 [GNU_AK_CONSTRUCTOR] = "constructor",
1250 [GNU_AK_DESTRUCTOR] = "destructor",
1251 [GNU_AK_NOTHROW] = "nothrow",
1252 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1253 [GNU_AK_COMMON] = "common",
1254 [GNU_AK_NOCOMMON] = "nocommon",
1255 [GNU_AK_PACKED] = "packed",
1256 [GNU_AK_SHARED] = "shared",
1257 [GNU_AK_NOTSHARED] = "notshared",
1258 [GNU_AK_USED] = "used",
1259 [GNU_AK_UNUSED] = "unused",
1260 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1261 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1262 [GNU_AK_LONGCALL] = "longcall",
1263 [GNU_AK_SHORTCALL] = "shortcall",
1264 [GNU_AK_LONG_CALL] = "long_call",
1265 [GNU_AK_SHORT_CALL] = "short_call",
1266 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1267 [GNU_AK_INTERRUPT] = "interrupt",
1268 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1269 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1270 [GNU_AK_NESTING] = "nesting",
1271 [GNU_AK_NEAR] = "near",
1272 [GNU_AK_FAR] = "far",
1273 [GNU_AK_SIGNAL] = "signal",
1274 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1275 [GNU_AK_TINY_DATA] = "tiny_data",
1276 [GNU_AK_SAVEALL] = "saveall",
1277 [GNU_AK_FLATTEN] = "flatten",
1278 [GNU_AK_SSEREGPARM] = "sseregparm",
1279 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1280 [GNU_AK_RETURN_TWICE] = "return_twice",
1281 [GNU_AK_MAY_ALIAS] = "may_alias",
1282 [GNU_AK_MS_STRUCT] = "ms_struct",
1283 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1284 [GNU_AK_DLLIMPORT] = "dllimport",
1285 [GNU_AK_DLLEXPORT] = "dllexport",
1286 [GNU_AK_ALIGNED] = "aligned",
1287 [GNU_AK_ALIAS] = "alias",
1288 [GNU_AK_SECTION] = "section",
1289 [GNU_AK_FORMAT] = "format",
1290 [GNU_AK_FORMAT_ARG] = "format_arg",
1291 [GNU_AK_WEAKREF] = "weakref",
1292 [GNU_AK_NONNULL] = "nonnull",
1293 [GNU_AK_TLS_MODEL] = "tls_model",
1294 [GNU_AK_VISIBILITY] = "visibility",
1295 [GNU_AK_REGPARM] = "regparm",
1296 [GNU_AK_MODE] = "mode",
1297 [GNU_AK_MODEL] = "model",
1298 [GNU_AK_TRAP_EXIT] = "trap_exit",
1299 [GNU_AK_SP_SWITCH] = "sp_switch",
1300 [GNU_AK_SENTINEL] = "sentinel"
1304 * compare two string, ignoring double underscores on the second.
1306 static int strcmp_underscore(const char *s1, const char *s2)
1308 if (s2[0] == '_' && s2[1] == '_') {
1309 size_t len2 = strlen(s2);
1310 size_t len1 = strlen(s1);
1311 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1312 return strncmp(s1, s2+2, len2-4);
1316 return strcmp(s1, s2);
1320 * Allocate a new gnu temporal attribute of given kind.
1322 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1324 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1325 attribute->kind = kind;
1326 attribute->next = NULL;
1327 attribute->invalid = false;
1328 attribute->have_arguments = false;
1334 * Parse one constant expression argument of the given attribute.
1336 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1338 expression_t *expression;
1339 add_anchor_token(')');
1340 expression = parse_constant_expression();
1341 rem_anchor_token(')');
1343 attribute->u.argument = fold_constant(expression);
1346 attribute->invalid = true;
1350 * Parse a list of constant expressions arguments of the given attribute.
1352 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1354 argument_list_t **list = &attribute->u.arguments;
1355 argument_list_t *entry;
1356 expression_t *expression;
1357 add_anchor_token(')');
1358 add_anchor_token(',');
1360 expression = parse_constant_expression();
1361 entry = obstack_alloc(&temp_obst, sizeof(entry));
1362 entry->argument = fold_constant(expression);
1365 list = &entry->next;
1366 if (token.type != ',')
1370 rem_anchor_token(',');
1371 rem_anchor_token(')');
1375 attribute->invalid = true;
1379 * Parse one string literal argument of the given attribute.
1381 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1384 add_anchor_token('(');
1385 if (token.type != T_STRING_LITERAL) {
1386 parse_error_expected("while parsing attribute directive",
1387 T_STRING_LITERAL, NULL);
1390 *string = parse_string_literals();
1391 rem_anchor_token('(');
1395 attribute->invalid = true;
1399 * Parse one tls model of the given attribute.
1401 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1403 static const char *const tls_models[] = {
1409 string_t string = { NULL, 0 };
1410 parse_gnu_attribute_string_arg(attribute, &string);
1411 if (string.begin != NULL) {
1412 for (size_t i = 0; i < 4; ++i) {
1413 if (strcmp(tls_models[i], string.begin) == 0) {
1414 attribute->u.value = i;
1418 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1420 attribute->invalid = true;
1424 * Parse one tls model of the given attribute.
1426 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1428 static const char *const visibilities[] = {
1434 string_t string = { NULL, 0 };
1435 parse_gnu_attribute_string_arg(attribute, &string);
1436 if (string.begin != NULL) {
1437 for (size_t i = 0; i < 4; ++i) {
1438 if (strcmp(visibilities[i], string.begin) == 0) {
1439 attribute->u.value = i;
1443 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1445 attribute->invalid = true;
1449 * Parse one (code) model of the given attribute.
1451 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1453 static const char *const visibilities[] = {
1458 string_t string = { NULL, 0 };
1459 parse_gnu_attribute_string_arg(attribute, &string);
1460 if (string.begin != NULL) {
1461 for (int i = 0; i < 3; ++i) {
1462 if (strcmp(visibilities[i], string.begin) == 0) {
1463 attribute->u.value = i;
1467 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1469 attribute->invalid = true;
1473 * Parse one mode of the given attribute.
1475 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1477 /* TODO: find out what is allowed here... */
1479 /* at least: byte, word, pointer, list of machine modes
1480 * __XXX___ is interpreted as XXX */
1481 add_anchor_token(')');
1483 if (token.type != T_IDENTIFIER) {
1484 expect(T_IDENTIFIER);
1487 /* This isn't really correct, the backend should provide a list of machine
1488 * specific modes (according to gcc philosophy that is...) */
1489 const char *symbol_str = token.v.symbol->string;
1490 if (strcmp_underscore("QI", symbol_str) == 0 ||
1491 strcmp_underscore("byte", symbol_str) == 0) {
1492 attribute->u.akind = ATOMIC_TYPE_CHAR;
1493 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1494 attribute->u.akind = ATOMIC_TYPE_SHORT;
1495 } else if (strcmp_underscore("SI", symbol_str) == 0
1496 || strcmp_underscore("word", symbol_str) == 0
1497 || strcmp_underscore("pointer", symbol_str) == 0) {
1498 attribute->u.akind = ATOMIC_TYPE_INT;
1499 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1500 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1503 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1504 attribute->invalid = true;
1508 rem_anchor_token(')');
1512 attribute->invalid = true;
1516 * Parse one interrupt argument of the given attribute.
1518 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1520 static const char *const interrupts[] = {
1527 string_t string = { NULL, 0 };
1528 parse_gnu_attribute_string_arg(attribute, &string);
1529 if (string.begin != NULL) {
1530 for (size_t i = 0; i < 5; ++i) {
1531 if (strcmp(interrupts[i], string.begin) == 0) {
1532 attribute->u.value = i;
1536 errorf(HERE, "'%s' is not an interrupt", string.begin);
1538 attribute->invalid = true;
1542 * Parse ( identifier, const expression, const expression )
1544 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1546 static const char *const format_names[] = {
1554 if (token.type != T_IDENTIFIER) {
1555 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1558 const char *name = token.v.symbol->string;
1559 for (i = 0; i < 4; ++i) {
1560 if (strcmp_underscore(format_names[i], name) == 0)
1564 if (warning.attribute)
1565 warningf(HERE, "'%s' is an unrecognized format function type", name);
1570 add_anchor_token(')');
1571 add_anchor_token(',');
1572 parse_constant_expression();
1573 rem_anchor_token(',');
1574 rem_anchor_token(')');
1577 add_anchor_token(')');
1578 parse_constant_expression();
1579 rem_anchor_token(')');
1583 attribute->u.value = true;
1587 * Check that a given GNU attribute has no arguments.
1589 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1591 if (!attribute->have_arguments)
1594 /* should have no arguments */
1595 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1596 eat_until_matching_token('(');
1597 /* we have already consumed '(', so we stop before ')', eat it */
1599 attribute->invalid = true;
1603 * Parse one GNU attribute.
1605 * Note that attribute names can be specified WITH or WITHOUT
1606 * double underscores, ie const or __const__.
1608 * The following attributes are parsed without arguments
1633 * no_instrument_function
1634 * warn_unused_result
1651 * externally_visible
1659 * The following attributes are parsed with arguments
1660 * aligned( const expression )
1661 * alias( string literal )
1662 * section( string literal )
1663 * format( identifier, const expression, const expression )
1664 * format_arg( const expression )
1665 * tls_model( string literal )
1666 * visibility( string literal )
1667 * regparm( const expression )
1668 * model( string leteral )
1669 * trap_exit( const expression )
1670 * sp_switch( string literal )
1672 * The following attributes might have arguments
1673 * weak_ref( string literal )
1674 * non_null( const expression // ',' )
1675 * interrupt( string literal )
1676 * sentinel( constant expression )
1678 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1680 gnu_attribute_t *head = *attributes;
1681 gnu_attribute_t *last = *attributes;
1682 decl_modifiers_t modifiers = 0;
1683 gnu_attribute_t *attribute;
1685 eat(T___attribute__);
1689 if (token.type != ')') {
1690 /* find the end of the list */
1692 while (last->next != NULL)
1696 /* non-empty attribute list */
1699 if (token.type == T_const) {
1701 } else if (token.type == T_volatile) {
1703 } else if (token.type == T_cdecl) {
1704 /* __attribute__((cdecl)), WITH ms mode */
1706 } else if (token.type == T_IDENTIFIER) {
1707 const symbol_t *sym = token.v.symbol;
1710 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1717 for (i = 0; i < GNU_AK_LAST; ++i) {
1718 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1721 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1724 if (kind == GNU_AK_LAST) {
1725 if (warning.attribute)
1726 warningf(HERE, "'%s' attribute directive ignored", name);
1728 /* skip possible arguments */
1729 if (token.type == '(') {
1730 eat_until_matching_token(')');
1733 /* check for arguments */
1734 attribute = allocate_gnu_attribute(kind);
1735 if (token.type == '(') {
1737 if (token.type == ')') {
1738 /* empty args are allowed */
1741 attribute->have_arguments = true;
1745 case GNU_AK_VOLATILE:
1750 case GNU_AK_NOCOMMON:
1752 case GNU_AK_NOTSHARED:
1753 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1754 case GNU_AK_WARN_UNUSED_RESULT:
1755 case GNU_AK_LONGCALL:
1756 case GNU_AK_SHORTCALL:
1757 case GNU_AK_LONG_CALL:
1758 case GNU_AK_SHORT_CALL:
1759 case GNU_AK_FUNCTION_VECTOR:
1760 case GNU_AK_INTERRUPT_HANDLER:
1761 case GNU_AK_NMI_HANDLER:
1762 case GNU_AK_NESTING:
1766 case GNU_AK_EIGTHBIT_DATA:
1767 case GNU_AK_TINY_DATA:
1768 case GNU_AK_SAVEALL:
1769 case GNU_AK_FLATTEN:
1770 case GNU_AK_SSEREGPARM:
1771 case GNU_AK_EXTERNALLY_VISIBLE:
1772 case GNU_AK_RETURN_TWICE:
1773 case GNU_AK_MAY_ALIAS:
1774 case GNU_AK_MS_STRUCT:
1775 case GNU_AK_GCC_STRUCT:
1778 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1779 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1780 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1781 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1782 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1783 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1784 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1785 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1786 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1787 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1788 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1789 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1790 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1791 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1792 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1793 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1794 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1795 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1797 case GNU_AK_ALIGNED:
1798 /* __align__ may be used without an argument */
1799 if (attribute->have_arguments) {
1800 parse_gnu_attribute_const_arg(attribute);
1804 case GNU_AK_FORMAT_ARG:
1805 case GNU_AK_REGPARM:
1806 case GNU_AK_TRAP_EXIT:
1807 if (!attribute->have_arguments) {
1808 /* should have arguments */
1809 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1810 attribute->invalid = true;
1812 parse_gnu_attribute_const_arg(attribute);
1815 case GNU_AK_SECTION:
1816 case GNU_AK_SP_SWITCH:
1817 if (!attribute->have_arguments) {
1818 /* should have arguments */
1819 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1820 attribute->invalid = true;
1822 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1825 if (!attribute->have_arguments) {
1826 /* should have arguments */
1827 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1828 attribute->invalid = true;
1830 parse_gnu_attribute_format_args(attribute);
1832 case GNU_AK_WEAKREF:
1833 /* may have one string argument */
1834 if (attribute->have_arguments)
1835 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1837 case GNU_AK_NONNULL:
1838 if (attribute->have_arguments)
1839 parse_gnu_attribute_const_arg_list(attribute);
1841 case GNU_AK_TLS_MODEL:
1842 if (!attribute->have_arguments) {
1843 /* should have arguments */
1844 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1846 parse_gnu_attribute_tls_model_arg(attribute);
1848 case GNU_AK_VISIBILITY:
1849 if (!attribute->have_arguments) {
1850 /* should have arguments */
1851 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1853 parse_gnu_attribute_visibility_arg(attribute);
1856 if (!attribute->have_arguments) {
1857 /* should have arguments */
1858 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1860 parse_gnu_attribute_model_arg(attribute);
1864 if (!attribute->have_arguments) {
1865 /* should have arguments */
1866 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1868 parse_gnu_attribute_mode_arg(attribute);
1871 case GNU_AK_INTERRUPT:
1872 /* may have one string argument */
1873 if (attribute->have_arguments)
1874 parse_gnu_attribute_interrupt_arg(attribute);
1876 case GNU_AK_SENTINEL:
1877 /* may have one string argument */
1878 if (attribute->have_arguments)
1879 parse_gnu_attribute_const_arg(attribute);
1882 /* already handled */
1886 check_no_argument(attribute, name);
1889 if (attribute != NULL) {
1891 last->next = attribute;
1894 head = last = attribute;
1898 if (token.type != ',')
1912 * Parse GNU attributes.
1914 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1916 decl_modifiers_t modifiers = 0;
1919 switch (token.type) {
1920 case T___attribute__:
1921 modifiers |= parse_gnu_attribute(attributes);
1927 if (token.type != T_STRING_LITERAL) {
1928 parse_error_expected("while parsing assembler attribute",
1929 T_STRING_LITERAL, NULL);
1930 eat_until_matching_token('(');
1933 parse_string_literals();
1938 case T_cdecl: modifiers |= DM_CDECL; break;
1939 case T__fastcall: modifiers |= DM_FASTCALL; break;
1940 case T__stdcall: modifiers |= DM_STDCALL; break;
1943 /* TODO record modifier */
1945 warningf(HERE, "Ignoring declaration modifier %K", &token);
1949 default: return modifiers;
1956 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1958 static entity_t *determine_lhs_ent(expression_t *const expr,
1961 switch (expr->kind) {
1962 case EXPR_REFERENCE: {
1963 entity_t *const entity = expr->reference.entity;
1964 /* we should only find variables as lvalues... */
1965 if (entity->base.kind != ENTITY_VARIABLE
1966 && entity->base.kind != ENTITY_PARAMETER)
1972 case EXPR_ARRAY_ACCESS: {
1973 expression_t *const ref = expr->array_access.array_ref;
1974 entity_t * ent = NULL;
1975 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1976 ent = determine_lhs_ent(ref, lhs_ent);
1979 mark_vars_read(expr->select.compound, lhs_ent);
1981 mark_vars_read(expr->array_access.index, lhs_ent);
1986 if (is_type_compound(skip_typeref(expr->base.type))) {
1987 return determine_lhs_ent(expr->select.compound, lhs_ent);
1989 mark_vars_read(expr->select.compound, lhs_ent);
1994 case EXPR_UNARY_DEREFERENCE: {
1995 expression_t *const val = expr->unary.value;
1996 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1998 return determine_lhs_ent(val->unary.value, lhs_ent);
2000 mark_vars_read(val, NULL);
2006 mark_vars_read(expr, NULL);
2011 #define ENT_ANY ((entity_t*)-1)
2014 * Mark declarations, which are read. This is used to detect variables, which
2018 * x is not marked as "read", because it is only read to calculate its own new
2022 * x and y are not detected as "not read", because multiple variables are
2025 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
2027 switch (expr->kind) {
2028 case EXPR_REFERENCE: {
2029 entity_t *const entity = expr->reference.entity;
2030 if (entity->kind != ENTITY_VARIABLE
2031 && entity->kind != ENTITY_PARAMETER)
2034 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
2035 if (entity->kind == ENTITY_VARIABLE) {
2036 entity->variable.read = true;
2038 entity->parameter.read = true;
2045 // TODO respect pure/const
2046 mark_vars_read(expr->call.function, NULL);
2047 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2048 mark_vars_read(arg->expression, NULL);
2052 case EXPR_CONDITIONAL:
2053 // TODO lhs_decl should depend on whether true/false have an effect
2054 mark_vars_read(expr->conditional.condition, NULL);
2055 if (expr->conditional.true_expression != NULL)
2056 mark_vars_read(expr->conditional.true_expression, lhs_ent);
2057 mark_vars_read(expr->conditional.false_expression, lhs_ent);
2061 if (lhs_ent == ENT_ANY
2062 && !is_type_compound(skip_typeref(expr->base.type)))
2064 mark_vars_read(expr->select.compound, lhs_ent);
2067 case EXPR_ARRAY_ACCESS: {
2068 expression_t *const ref = expr->array_access.array_ref;
2069 mark_vars_read(ref, lhs_ent);
2070 lhs_ent = determine_lhs_ent(ref, lhs_ent);
2071 mark_vars_read(expr->array_access.index, lhs_ent);
2076 mark_vars_read(expr->va_arge.ap, lhs_ent);
2079 case EXPR_UNARY_CAST:
2080 /* Special case: Use void cast to mark a variable as "read" */
2081 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2086 case EXPR_UNARY_THROW:
2087 if (expr->unary.value == NULL)
2090 case EXPR_UNARY_DEREFERENCE:
2091 case EXPR_UNARY_DELETE:
2092 case EXPR_UNARY_DELETE_ARRAY:
2093 if (lhs_ent == ENT_ANY)
2097 case EXPR_UNARY_NEGATE:
2098 case EXPR_UNARY_PLUS:
2099 case EXPR_UNARY_BITWISE_NEGATE:
2100 case EXPR_UNARY_NOT:
2101 case EXPR_UNARY_TAKE_ADDRESS:
2102 case EXPR_UNARY_POSTFIX_INCREMENT:
2103 case EXPR_UNARY_POSTFIX_DECREMENT:
2104 case EXPR_UNARY_PREFIX_INCREMENT:
2105 case EXPR_UNARY_PREFIX_DECREMENT:
2106 case EXPR_UNARY_CAST_IMPLICIT:
2107 case EXPR_UNARY_ASSUME:
2109 mark_vars_read(expr->unary.value, lhs_ent);
2112 case EXPR_BINARY_ADD:
2113 case EXPR_BINARY_SUB:
2114 case EXPR_BINARY_MUL:
2115 case EXPR_BINARY_DIV:
2116 case EXPR_BINARY_MOD:
2117 case EXPR_BINARY_EQUAL:
2118 case EXPR_BINARY_NOTEQUAL:
2119 case EXPR_BINARY_LESS:
2120 case EXPR_BINARY_LESSEQUAL:
2121 case EXPR_BINARY_GREATER:
2122 case EXPR_BINARY_GREATEREQUAL:
2123 case EXPR_BINARY_BITWISE_AND:
2124 case EXPR_BINARY_BITWISE_OR:
2125 case EXPR_BINARY_BITWISE_XOR:
2126 case EXPR_BINARY_LOGICAL_AND:
2127 case EXPR_BINARY_LOGICAL_OR:
2128 case EXPR_BINARY_SHIFTLEFT:
2129 case EXPR_BINARY_SHIFTRIGHT:
2130 case EXPR_BINARY_COMMA:
2131 case EXPR_BINARY_ISGREATER:
2132 case EXPR_BINARY_ISGREATEREQUAL:
2133 case EXPR_BINARY_ISLESS:
2134 case EXPR_BINARY_ISLESSEQUAL:
2135 case EXPR_BINARY_ISLESSGREATER:
2136 case EXPR_BINARY_ISUNORDERED:
2137 mark_vars_read(expr->binary.left, lhs_ent);
2138 mark_vars_read(expr->binary.right, lhs_ent);
2141 case EXPR_BINARY_ASSIGN:
2142 case EXPR_BINARY_MUL_ASSIGN:
2143 case EXPR_BINARY_DIV_ASSIGN:
2144 case EXPR_BINARY_MOD_ASSIGN:
2145 case EXPR_BINARY_ADD_ASSIGN:
2146 case EXPR_BINARY_SUB_ASSIGN:
2147 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2148 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2149 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2150 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2151 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2152 if (lhs_ent == ENT_ANY)
2154 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
2155 mark_vars_read(expr->binary.right, lhs_ent);
2160 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
2166 case EXPR_CHARACTER_CONSTANT:
2167 case EXPR_WIDE_CHARACTER_CONSTANT:
2168 case EXPR_STRING_LITERAL:
2169 case EXPR_WIDE_STRING_LITERAL:
2170 case EXPR_COMPOUND_LITERAL: // TODO init?
2172 case EXPR_CLASSIFY_TYPE:
2175 case EXPR_BUILTIN_SYMBOL:
2176 case EXPR_BUILTIN_CONSTANT_P:
2177 case EXPR_BUILTIN_PREFETCH:
2179 case EXPR_STATEMENT: // TODO
2180 case EXPR_LABEL_ADDRESS:
2181 case EXPR_REFERENCE_ENUM_VALUE:
2185 panic("unhandled expression");
2188 static designator_t *parse_designation(void)
2190 designator_t *result = NULL;
2191 designator_t *last = NULL;
2194 designator_t *designator;
2195 switch (token.type) {
2197 designator = allocate_ast_zero(sizeof(designator[0]));
2198 designator->source_position = token.source_position;
2200 add_anchor_token(']');
2201 designator->array_index = parse_constant_expression();
2202 rem_anchor_token(']');
2206 designator = allocate_ast_zero(sizeof(designator[0]));
2207 designator->source_position = token.source_position;
2209 if (token.type != T_IDENTIFIER) {
2210 parse_error_expected("while parsing designator",
2211 T_IDENTIFIER, NULL);
2214 designator->symbol = token.v.symbol;
2222 assert(designator != NULL);
2224 last->next = designator;
2226 result = designator;
2234 static initializer_t *initializer_from_string(array_type_t *type,
2235 const string_t *const string)
2237 /* TODO: check len vs. size of array type */
2240 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2241 initializer->string.string = *string;
2246 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2247 wide_string_t *const string)
2249 /* TODO: check len vs. size of array type */
2252 initializer_t *const initializer =
2253 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2254 initializer->wide_string.string = *string;
2260 * Build an initializer from a given expression.
2262 static initializer_t *initializer_from_expression(type_t *orig_type,
2263 expression_t *expression)
2265 /* TODO check that expression is a constant expression */
2267 /* § 6.7.8.14/15 char array may be initialized by string literals */
2268 type_t *type = skip_typeref(orig_type);
2269 type_t *expr_type_orig = expression->base.type;
2270 type_t *expr_type = skip_typeref(expr_type_orig);
2271 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2272 array_type_t *const array_type = &type->array;
2273 type_t *const element_type = skip_typeref(array_type->element_type);
2275 if (element_type->kind == TYPE_ATOMIC) {
2276 atomic_type_kind_t akind = element_type->atomic.akind;
2277 switch (expression->kind) {
2278 case EXPR_STRING_LITERAL:
2279 if (akind == ATOMIC_TYPE_CHAR
2280 || akind == ATOMIC_TYPE_SCHAR
2281 || akind == ATOMIC_TYPE_UCHAR) {
2282 return initializer_from_string(array_type,
2283 &expression->string.value);
2286 case EXPR_WIDE_STRING_LITERAL: {
2287 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2288 if (get_unqualified_type(element_type) == bare_wchar_type) {
2289 return initializer_from_wide_string(array_type,
2290 &expression->wide_string.value);
2300 assign_error_t error = semantic_assign(type, expression);
2301 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2303 report_assign_error(error, type, expression, "initializer",
2304 &expression->base.source_position);
2306 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2308 if (type->kind == TYPE_BITFIELD) {
2309 type = type->bitfield.base_type;
2312 result->value.value = create_implicit_cast(expression, type);
2318 * Checks if a given expression can be used as an constant initializer.
2320 static bool is_initializer_constant(const expression_t *expression)
2322 return is_constant_expression(expression)
2323 || is_address_constant(expression);
2327 * Parses an scalar initializer.
2329 * § 6.7.8.11; eat {} without warning
2331 static initializer_t *parse_scalar_initializer(type_t *type,
2332 bool must_be_constant)
2334 /* there might be extra {} hierarchies */
2336 if (token.type == '{') {
2338 warningf(HERE, "extra curly braces around scalar initializer");
2342 } while (token.type == '{');
2345 expression_t *expression = parse_assignment_expression();
2346 mark_vars_read(expression, NULL);
2347 if (must_be_constant && !is_initializer_constant(expression)) {
2348 errorf(&expression->base.source_position,
2349 "Initialisation expression '%E' is not constant",
2353 initializer_t *initializer = initializer_from_expression(type, expression);
2355 if (initializer == NULL) {
2356 errorf(&expression->base.source_position,
2357 "expression '%E' (type '%T') doesn't match expected type '%T'",
2358 expression, expression->base.type, type);
2363 bool additional_warning_displayed = false;
2364 while (braces > 0) {
2365 if (token.type == ',') {
2368 if (token.type != '}') {
2369 if (!additional_warning_displayed && warning.other) {
2370 warningf(HERE, "additional elements in scalar initializer");
2371 additional_warning_displayed = true;
2382 * An entry in the type path.
2384 typedef struct type_path_entry_t type_path_entry_t;
2385 struct type_path_entry_t {
2386 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2388 size_t index; /**< For array types: the current index. */
2389 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2394 * A type path expression a position inside compound or array types.
2396 typedef struct type_path_t type_path_t;
2397 struct type_path_t {
2398 type_path_entry_t *path; /**< An flexible array containing the current path. */
2399 type_t *top_type; /**< type of the element the path points */
2400 size_t max_index; /**< largest index in outermost array */
2404 * Prints a type path for debugging.
2406 static __attribute__((unused)) void debug_print_type_path(
2407 const type_path_t *path)
2409 size_t len = ARR_LEN(path->path);
2411 for (size_t i = 0; i < len; ++i) {
2412 const type_path_entry_t *entry = & path->path[i];
2414 type_t *type = skip_typeref(entry->type);
2415 if (is_type_compound(type)) {
2416 /* in gcc mode structs can have no members */
2417 if (entry->v.compound_entry == NULL) {
2421 fprintf(stderr, ".%s",
2422 entry->v.compound_entry->base.symbol->string);
2423 } else if (is_type_array(type)) {
2424 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2426 fprintf(stderr, "-INVALID-");
2429 if (path->top_type != NULL) {
2430 fprintf(stderr, " (");
2431 print_type(path->top_type);
2432 fprintf(stderr, ")");
2437 * Return the top type path entry, ie. in a path
2438 * (type).a.b returns the b.
2440 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2442 size_t len = ARR_LEN(path->path);
2444 return &path->path[len-1];
2448 * Enlarge the type path by an (empty) element.
2450 static type_path_entry_t *append_to_type_path(type_path_t *path)
2452 size_t len = ARR_LEN(path->path);
2453 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2455 type_path_entry_t *result = & path->path[len];
2456 memset(result, 0, sizeof(result[0]));
2461 * Descending into a sub-type. Enter the scope of the current top_type.
2463 static void descend_into_subtype(type_path_t *path)
2465 type_t *orig_top_type = path->top_type;
2466 type_t *top_type = skip_typeref(orig_top_type);
2468 type_path_entry_t *top = append_to_type_path(path);
2469 top->type = top_type;
2471 if (is_type_compound(top_type)) {
2472 compound_t *compound = top_type->compound.compound;
2473 entity_t *entry = compound->members.entities;
2475 if (entry != NULL) {
2476 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2477 top->v.compound_entry = &entry->declaration;
2478 path->top_type = entry->declaration.type;
2480 path->top_type = NULL;
2482 } else if (is_type_array(top_type)) {
2484 path->top_type = top_type->array.element_type;
2486 assert(!is_type_valid(top_type));
2491 * Pop an entry from the given type path, ie. returning from
2492 * (type).a.b to (type).a
2494 static void ascend_from_subtype(type_path_t *path)
2496 type_path_entry_t *top = get_type_path_top(path);
2498 path->top_type = top->type;
2500 size_t len = ARR_LEN(path->path);
2501 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2505 * Pop entries from the given type path until the given
2506 * path level is reached.
2508 static void ascend_to(type_path_t *path, size_t top_path_level)
2510 size_t len = ARR_LEN(path->path);
2512 while (len > top_path_level) {
2513 ascend_from_subtype(path);
2514 len = ARR_LEN(path->path);
2518 static bool walk_designator(type_path_t *path, const designator_t *designator,
2519 bool used_in_offsetof)
2521 for (; designator != NULL; designator = designator->next) {
2522 type_path_entry_t *top = get_type_path_top(path);
2523 type_t *orig_type = top->type;
2525 type_t *type = skip_typeref(orig_type);
2527 if (designator->symbol != NULL) {
2528 symbol_t *symbol = designator->symbol;
2529 if (!is_type_compound(type)) {
2530 if (is_type_valid(type)) {
2531 errorf(&designator->source_position,
2532 "'.%Y' designator used for non-compound type '%T'",
2536 top->type = type_error_type;
2537 top->v.compound_entry = NULL;
2538 orig_type = type_error_type;
2540 compound_t *compound = type->compound.compound;
2541 entity_t *iter = compound->members.entities;
2542 for (; iter != NULL; iter = iter->base.next) {
2543 if (iter->base.symbol == symbol) {
2548 errorf(&designator->source_position,
2549 "'%T' has no member named '%Y'", orig_type, symbol);
2552 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2553 if (used_in_offsetof) {
2554 type_t *real_type = skip_typeref(iter->declaration.type);
2555 if (real_type->kind == TYPE_BITFIELD) {
2556 errorf(&designator->source_position,
2557 "offsetof designator '%Y' may not specify bitfield",
2563 top->type = orig_type;
2564 top->v.compound_entry = &iter->declaration;
2565 orig_type = iter->declaration.type;
2568 expression_t *array_index = designator->array_index;
2569 assert(designator->array_index != NULL);
2571 if (!is_type_array(type)) {
2572 if (is_type_valid(type)) {
2573 errorf(&designator->source_position,
2574 "[%E] designator used for non-array type '%T'",
2575 array_index, orig_type);
2580 long index = fold_constant(array_index);
2581 if (!used_in_offsetof) {
2583 errorf(&designator->source_position,
2584 "array index [%E] must be positive", array_index);
2585 } else if (type->array.size_constant) {
2586 long array_size = type->array.size;
2587 if (index >= array_size) {
2588 errorf(&designator->source_position,
2589 "designator [%E] (%d) exceeds array size %d",
2590 array_index, index, array_size);
2595 top->type = orig_type;
2596 top->v.index = (size_t) index;
2597 orig_type = type->array.element_type;
2599 path->top_type = orig_type;
2601 if (designator->next != NULL) {
2602 descend_into_subtype(path);
2611 static void advance_current_object(type_path_t *path, size_t top_path_level)
2613 type_path_entry_t *top = get_type_path_top(path);
2615 type_t *type = skip_typeref(top->type);
2616 if (is_type_union(type)) {
2617 /* in unions only the first element is initialized */
2618 top->v.compound_entry = NULL;
2619 } else if (is_type_struct(type)) {
2620 declaration_t *entry = top->v.compound_entry;
2622 entity_t *next_entity = entry->base.next;
2623 if (next_entity != NULL) {
2624 assert(is_declaration(next_entity));
2625 entry = &next_entity->declaration;
2630 top->v.compound_entry = entry;
2631 if (entry != NULL) {
2632 path->top_type = entry->type;
2635 } else if (is_type_array(type)) {
2636 assert(is_type_array(type));
2640 if (!type->array.size_constant || top->v.index < type->array.size) {
2644 assert(!is_type_valid(type));
2648 /* we're past the last member of the current sub-aggregate, try if we
2649 * can ascend in the type hierarchy and continue with another subobject */
2650 size_t len = ARR_LEN(path->path);
2652 if (len > top_path_level) {
2653 ascend_from_subtype(path);
2654 advance_current_object(path, top_path_level);
2656 path->top_type = NULL;
2661 * skip until token is found.
2663 static void skip_until(int type)
2665 while (token.type != type) {
2666 if (token.type == T_EOF)
2673 * skip any {...} blocks until a closing bracket is reached.
2675 static void skip_initializers(void)
2677 if (token.type == '{')
2680 while (token.type != '}') {
2681 if (token.type == T_EOF)
2683 if (token.type == '{') {
2691 static initializer_t *create_empty_initializer(void)
2693 static initializer_t empty_initializer
2694 = { .list = { { INITIALIZER_LIST }, 0 } };
2695 return &empty_initializer;
2699 * Parse a part of an initialiser for a struct or union,
2701 static initializer_t *parse_sub_initializer(type_path_t *path,
2702 type_t *outer_type, size_t top_path_level,
2703 parse_initializer_env_t *env)
2705 if (token.type == '}') {
2706 /* empty initializer */
2707 return create_empty_initializer();
2710 type_t *orig_type = path->top_type;
2711 type_t *type = NULL;
2713 if (orig_type == NULL) {
2714 /* We are initializing an empty compound. */
2716 type = skip_typeref(orig_type);
2719 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2722 designator_t *designator = NULL;
2723 if (token.type == '.' || token.type == '[') {
2724 designator = parse_designation();
2725 goto finish_designator;
2726 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2727 /* GNU-style designator ("identifier: value") */
2728 designator = allocate_ast_zero(sizeof(designator[0]));
2729 designator->source_position = token.source_position;
2730 designator->symbol = token.v.symbol;
2735 /* reset path to toplevel, evaluate designator from there */
2736 ascend_to(path, top_path_level);
2737 if (!walk_designator(path, designator, false)) {
2738 /* can't continue after designation error */
2742 initializer_t *designator_initializer
2743 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2744 designator_initializer->designator.designator = designator;
2745 ARR_APP1(initializer_t*, initializers, designator_initializer);
2747 orig_type = path->top_type;
2748 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2753 if (token.type == '{') {
2754 if (type != NULL && is_type_scalar(type)) {
2755 sub = parse_scalar_initializer(type, env->must_be_constant);
2759 if (env->entity != NULL) {
2761 "extra brace group at end of initializer for '%Y'",
2762 env->entity->base.symbol);
2764 errorf(HERE, "extra brace group at end of initializer");
2767 descend_into_subtype(path);
2769 add_anchor_token('}');
2770 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2772 rem_anchor_token('}');
2775 ascend_from_subtype(path);
2779 goto error_parse_next;
2783 /* must be an expression */
2784 expression_t *expression = parse_assignment_expression();
2786 if (env->must_be_constant && !is_initializer_constant(expression)) {
2787 errorf(&expression->base.source_position,
2788 "Initialisation expression '%E' is not constant",
2793 /* we are already outside, ... */
2794 type_t *const outer_type_skip = skip_typeref(outer_type);
2795 if (is_type_compound(outer_type_skip) &&
2796 !outer_type_skip->compound.compound->complete) {
2797 goto error_parse_next;
2802 /* handle { "string" } special case */
2803 if ((expression->kind == EXPR_STRING_LITERAL
2804 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2805 && outer_type != NULL) {
2806 sub = initializer_from_expression(outer_type, expression);
2808 if (token.type == ',') {
2811 if (token.type != '}' && warning.other) {
2812 warningf(HERE, "excessive elements in initializer for type '%T'",
2815 /* TODO: eat , ... */
2820 /* descend into subtypes until expression matches type */
2822 orig_type = path->top_type;
2823 type = skip_typeref(orig_type);
2825 sub = initializer_from_expression(orig_type, expression);
2829 if (!is_type_valid(type)) {
2832 if (is_type_scalar(type)) {
2833 errorf(&expression->base.source_position,
2834 "expression '%E' doesn't match expected type '%T'",
2835 expression, orig_type);
2839 descend_into_subtype(path);
2843 /* update largest index of top array */
2844 const type_path_entry_t *first = &path->path[0];
2845 type_t *first_type = first->type;
2846 first_type = skip_typeref(first_type);
2847 if (is_type_array(first_type)) {
2848 size_t index = first->v.index;
2849 if (index > path->max_index)
2850 path->max_index = index;
2854 /* append to initializers list */
2855 ARR_APP1(initializer_t*, initializers, sub);
2858 if (warning.other) {
2859 if (env->entity != NULL) {
2860 warningf(HERE, "excess elements in struct initializer for '%Y'",
2861 env->entity->base.symbol);
2863 warningf(HERE, "excess elements in struct initializer");
2869 if (token.type == '}') {
2873 if (token.type == '}') {
2878 /* advance to the next declaration if we are not at the end */
2879 advance_current_object(path, top_path_level);
2880 orig_type = path->top_type;
2881 if (orig_type != NULL)
2882 type = skip_typeref(orig_type);
2888 size_t len = ARR_LEN(initializers);
2889 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2890 initializer_t *result = allocate_ast_zero(size);
2891 result->kind = INITIALIZER_LIST;
2892 result->list.len = len;
2893 memcpy(&result->list.initializers, initializers,
2894 len * sizeof(initializers[0]));
2896 DEL_ARR_F(initializers);
2897 ascend_to(path, top_path_level+1);
2902 skip_initializers();
2903 DEL_ARR_F(initializers);
2904 ascend_to(path, top_path_level+1);
2909 * Parses an initializer. Parsers either a compound literal
2910 * (env->declaration == NULL) or an initializer of a declaration.
2912 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2914 type_t *type = skip_typeref(env->type);
2915 initializer_t *result = NULL;
2918 if (is_type_scalar(type)) {
2919 result = parse_scalar_initializer(type, env->must_be_constant);
2920 } else if (token.type == '{') {
2924 memset(&path, 0, sizeof(path));
2925 path.top_type = env->type;
2926 path.path = NEW_ARR_F(type_path_entry_t, 0);
2928 descend_into_subtype(&path);
2930 add_anchor_token('}');
2931 result = parse_sub_initializer(&path, env->type, 1, env);
2932 rem_anchor_token('}');
2934 max_index = path.max_index;
2935 DEL_ARR_F(path.path);
2939 /* parse_scalar_initializer() also works in this case: we simply
2940 * have an expression without {} around it */
2941 result = parse_scalar_initializer(type, env->must_be_constant);
2944 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2945 * the array type size */
2946 if (is_type_array(type) && type->array.size_expression == NULL
2947 && result != NULL) {
2949 switch (result->kind) {
2950 case INITIALIZER_LIST:
2951 size = max_index + 1;
2954 case INITIALIZER_STRING:
2955 size = result->string.string.size;
2958 case INITIALIZER_WIDE_STRING:
2959 size = result->wide_string.string.size;
2962 case INITIALIZER_DESIGNATOR:
2963 case INITIALIZER_VALUE:
2964 /* can happen for parse errors */
2969 internal_errorf(HERE, "invalid initializer type");
2972 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2973 cnst->base.type = type_size_t;
2974 cnst->conste.v.int_value = size;
2976 type_t *new_type = duplicate_type(type);
2978 new_type->array.size_expression = cnst;
2979 new_type->array.size_constant = true;
2980 new_type->array.has_implicit_size = true;
2981 new_type->array.size = size;
2982 env->type = new_type;
2990 static void append_entity(scope_t *scope, entity_t *entity)
2992 if (scope->last_entity != NULL) {
2993 scope->last_entity->base.next = entity;
2995 scope->entities = entity;
2997 scope->last_entity = entity;
3001 static compound_t *parse_compound_type_specifier(bool is_struct)
3003 gnu_attribute_t *attributes = NULL;
3004 decl_modifiers_t modifiers = 0;
3011 symbol_t *symbol = NULL;
3012 compound_t *compound = NULL;
3014 if (token.type == T___attribute__) {
3015 modifiers |= parse_attributes(&attributes);
3018 if (token.type == T_IDENTIFIER) {
3019 symbol = token.v.symbol;
3022 namespace_tag_t const namespc =
3023 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
3024 entity_t *entity = get_entity(symbol, namespc);
3025 if (entity != NULL) {
3026 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
3027 compound = &entity->compound;
3028 if (compound->base.parent_scope != current_scope &&
3029 (token.type == '{' || token.type == ';')) {
3030 /* we're in an inner scope and have a definition. Override
3031 existing definition in outer scope */
3033 } else if (compound->complete && token.type == '{') {
3034 assert(symbol != NULL);
3035 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
3036 is_struct ? "struct" : "union", symbol,
3037 &compound->base.source_position);
3038 /* clear members in the hope to avoid further errors */
3039 compound->members.entities = NULL;
3042 } else if (token.type != '{') {
3044 parse_error_expected("while parsing struct type specifier",
3045 T_IDENTIFIER, '{', NULL);
3047 parse_error_expected("while parsing union type specifier",
3048 T_IDENTIFIER, '{', NULL);
3054 if (compound == NULL) {
3055 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3056 entity_t *entity = allocate_entity_zero(kind);
3057 compound = &entity->compound;
3059 compound->base.namespc =
3060 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3061 compound->base.source_position = token.source_position;
3062 compound->base.symbol = symbol;
3063 compound->base.parent_scope = current_scope;
3064 if (symbol != NULL) {
3065 environment_push(entity);
3067 append_entity(current_scope, entity);
3070 if (token.type == '{') {
3071 parse_compound_type_entries(compound);
3072 modifiers |= parse_attributes(&attributes);
3074 if (symbol == NULL) {
3075 assert(anonymous_entity == NULL);
3076 anonymous_entity = (entity_t*)compound;
3080 compound->modifiers |= modifiers;
3084 static void parse_enum_entries(type_t *const enum_type)
3088 if (token.type == '}') {
3089 errorf(HERE, "empty enum not allowed");
3094 add_anchor_token('}');
3096 if (token.type != T_IDENTIFIER) {
3097 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3099 rem_anchor_token('}');
3103 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3104 entity->enum_value.enum_type = enum_type;
3105 entity->base.symbol = token.v.symbol;
3106 entity->base.source_position = token.source_position;
3109 if (token.type == '=') {
3111 expression_t *value = parse_constant_expression();
3113 value = create_implicit_cast(value, enum_type);
3114 entity->enum_value.value = value;
3119 record_entity(entity, false);
3121 if (token.type != ',')
3124 } while (token.type != '}');
3125 rem_anchor_token('}');
3133 static type_t *parse_enum_specifier(void)
3135 gnu_attribute_t *attributes = NULL;
3140 if (token.type == T_IDENTIFIER) {
3141 symbol = token.v.symbol;
3144 entity = get_entity(symbol, NAMESPACE_ENUM);
3145 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3146 } else if (token.type != '{') {
3147 parse_error_expected("while parsing enum type specifier",
3148 T_IDENTIFIER, '{', NULL);
3155 if (entity == NULL) {
3156 entity = allocate_entity_zero(ENTITY_ENUM);
3157 entity->base.namespc = NAMESPACE_ENUM;
3158 entity->base.source_position = token.source_position;
3159 entity->base.symbol = symbol;
3160 entity->base.parent_scope = current_scope;
3163 type_t *const type = allocate_type_zero(TYPE_ENUM);
3164 type->enumt.enume = &entity->enume;
3166 if (token.type == '{') {
3167 if (entity->enume.complete) {
3168 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
3169 symbol, &entity->base.source_position);
3171 if (symbol != NULL) {
3172 environment_push(entity);
3174 append_entity(current_scope, entity);
3175 entity->enume.complete = true;
3177 parse_enum_entries(type);
3178 parse_attributes(&attributes);
3180 if (symbol == NULL) {
3181 assert(anonymous_entity == NULL);
3182 anonymous_entity = entity;
3184 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3185 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
3193 * if a symbol is a typedef to another type, return true
3195 static bool is_typedef_symbol(symbol_t *symbol)
3197 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3198 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3201 static type_t *parse_typeof(void)
3208 add_anchor_token(')');
3210 expression_t *expression = NULL;
3212 bool old_type_prop = in_type_prop;
3213 bool old_gcc_extension = in_gcc_extension;
3214 in_type_prop = true;
3216 while (token.type == T___extension__) {
3217 /* This can be a prefix to a typename or an expression. */
3219 in_gcc_extension = true;
3221 switch (token.type) {
3223 if (is_typedef_symbol(token.v.symbol)) {
3224 type = parse_typename();
3226 expression = parse_expression();
3227 type = expression->base.type;
3232 type = parse_typename();
3236 expression = parse_expression();
3237 type = expression->base.type;
3240 in_type_prop = old_type_prop;
3241 in_gcc_extension = old_gcc_extension;
3243 rem_anchor_token(')');
3246 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3247 typeof_type->typeoft.expression = expression;
3248 typeof_type->typeoft.typeof_type = type;
3255 typedef enum specifiers_t {
3256 SPECIFIER_SIGNED = 1 << 0,
3257 SPECIFIER_UNSIGNED = 1 << 1,
3258 SPECIFIER_LONG = 1 << 2,
3259 SPECIFIER_INT = 1 << 3,
3260 SPECIFIER_DOUBLE = 1 << 4,
3261 SPECIFIER_CHAR = 1 << 5,
3262 SPECIFIER_SHORT = 1 << 6,
3263 SPECIFIER_LONG_LONG = 1 << 7,
3264 SPECIFIER_FLOAT = 1 << 8,
3265 SPECIFIER_BOOL = 1 << 9,
3266 SPECIFIER_VOID = 1 << 10,
3267 SPECIFIER_INT8 = 1 << 11,
3268 SPECIFIER_INT16 = 1 << 12,
3269 SPECIFIER_INT32 = 1 << 13,
3270 SPECIFIER_INT64 = 1 << 14,
3271 SPECIFIER_INT128 = 1 << 15,
3272 SPECIFIER_COMPLEX = 1 << 16,
3273 SPECIFIER_IMAGINARY = 1 << 17,
3276 static type_t *create_builtin_type(symbol_t *const symbol,
3277 type_t *const real_type)
3279 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3280 type->builtin.symbol = symbol;
3281 type->builtin.real_type = real_type;
3283 type_t *result = typehash_insert(type);
3284 if (type != result) {
3291 static type_t *get_typedef_type(symbol_t *symbol)
3293 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3294 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3297 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3298 type->typedeft.typedefe = &entity->typedefe;
3304 * check for the allowed MS alignment values.
3306 static bool check_alignment_value(long long intvalue)
3308 if (intvalue < 1 || intvalue > 8192) {
3309 errorf(HERE, "illegal alignment value");
3312 unsigned v = (unsigned)intvalue;
3313 for (unsigned i = 1; i <= 8192; i += i) {
3317 errorf(HERE, "alignment must be power of two");
3321 #define DET_MOD(name, tag) do { \
3322 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3323 *modifiers |= tag; \
3326 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3328 decl_modifiers_t *modifiers = &specifiers->modifiers;
3331 if (token.type == T_restrict) {
3333 DET_MOD(restrict, DM_RESTRICT);
3335 } else if (token.type != T_IDENTIFIER)
3337 symbol_t *symbol = token.v.symbol;
3338 if (symbol == sym_align) {
3341 if (token.type != T_INTEGER)
3343 if (check_alignment_value(token.v.intvalue)) {
3344 if (specifiers->alignment != 0 && warning.other)
3345 warningf(HERE, "align used more than once");
3346 specifiers->alignment = (unsigned char)token.v.intvalue;
3350 } else if (symbol == sym_allocate) {
3353 if (token.type != T_IDENTIFIER)
3355 (void)token.v.symbol;
3357 } else if (symbol == sym_dllimport) {
3359 DET_MOD(dllimport, DM_DLLIMPORT);
3360 } else if (symbol == sym_dllexport) {
3362 DET_MOD(dllexport, DM_DLLEXPORT);
3363 } else if (symbol == sym_thread) {
3365 DET_MOD(thread, DM_THREAD);
3366 } else if (symbol == sym_naked) {
3368 DET_MOD(naked, DM_NAKED);
3369 } else if (symbol == sym_noinline) {
3371 DET_MOD(noinline, DM_NOINLINE);
3372 } else if (symbol == sym_noreturn) {
3374 DET_MOD(noreturn, DM_NORETURN);
3375 } else if (symbol == sym_nothrow) {
3377 DET_MOD(nothrow, DM_NOTHROW);
3378 } else if (symbol == sym_novtable) {
3380 DET_MOD(novtable, DM_NOVTABLE);
3381 } else if (symbol == sym_property) {
3385 bool is_get = false;
3386 if (token.type != T_IDENTIFIER)
3388 if (token.v.symbol == sym_get) {
3390 } else if (token.v.symbol == sym_put) {
3392 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3397 if (token.type != T_IDENTIFIER)
3400 if (specifiers->get_property_sym != NULL) {
3401 errorf(HERE, "get property name already specified");
3403 specifiers->get_property_sym = token.v.symbol;
3406 if (specifiers->put_property_sym != NULL) {
3407 errorf(HERE, "put property name already specified");
3409 specifiers->put_property_sym = token.v.symbol;
3413 if (token.type == ',') {
3420 } else if (symbol == sym_selectany) {
3422 DET_MOD(selectany, DM_SELECTANY);
3423 } else if (symbol == sym_uuid) {
3426 if (token.type != T_STRING_LITERAL)
3430 } else if (symbol == sym_deprecated) {
3432 if (specifiers->deprecated != 0 && warning.other)
3433 warningf(HERE, "deprecated used more than once");
3434 specifiers->deprecated = true;
3435 if (token.type == '(') {
3437 if (token.type == T_STRING_LITERAL) {
3438 specifiers->deprecated_string = token.v.string.begin;
3441 errorf(HERE, "string literal expected");
3445 } else if (symbol == sym_noalias) {
3447 DET_MOD(noalias, DM_NOALIAS);
3450 warningf(HERE, "Unknown modifier '%Y' ignored", token.v.symbol);
3452 if (token.type == '(')
3456 if (token.type == ',')
3463 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3465 entity_t *entity = allocate_entity_zero(kind);
3466 entity->base.source_position = *HERE;
3467 entity->base.symbol = symbol;
3468 if (is_declaration(entity)) {
3469 entity->declaration.type = type_error_type;
3470 entity->declaration.implicit = true;
3471 } else if (kind == ENTITY_TYPEDEF) {
3472 entity->typedefe.type = type_error_type;
3473 entity->typedefe.builtin = true;
3475 record_entity(entity, false);
3479 static void parse_microsoft_based(based_spec_t *based_spec)
3481 if (token.type != T_IDENTIFIER) {
3482 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3485 symbol_t *symbol = token.v.symbol;
3486 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3488 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3489 errorf(HERE, "'%Y' is not a variable name.", symbol);
3490 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3492 variable_t *variable = &entity->variable;
3494 if (based_spec->base_variable != NULL) {
3495 errorf(HERE, "__based type qualifier specified more than once");
3497 based_spec->source_position = token.source_position;
3498 based_spec->base_variable = variable;
3500 type_t *const type = variable->base.type;
3502 if (is_type_valid(type)) {
3503 if (! is_type_pointer(skip_typeref(type))) {
3504 errorf(HERE, "variable in __based modifier must have pointer type instead of '%T'", type);
3506 if (variable->base.base.parent_scope != file_scope) {
3507 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3515 * Finish the construction of a struct type by calculating
3516 * its size, offsets, alignment.
3518 static void finish_struct_type(compound_type_t *type)
3520 assert(type->compound != NULL);
3522 compound_t *compound = type->compound;
3523 if (!compound->complete)
3528 il_alignment_t alignment = 1;
3529 bool need_pad = false;
3531 entity_t *entry = compound->members.entities;
3532 for (; entry != NULL; entry = entry->base.next) {
3533 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3536 type_t *m_type = skip_typeref(entry->declaration.type);
3537 if (! is_type_valid(m_type)) {
3538 /* simply ignore errors here */
3541 il_alignment_t m_alignment = m_type->base.alignment;
3542 if (m_alignment > alignment)
3543 alignment = m_alignment;
3545 offset = (size + m_alignment - 1) & -m_alignment;
3549 entry->compound_member.offset = offset;
3550 size = offset + m_type->base.size;
3552 if (type->base.alignment != 0) {
3553 alignment = type->base.alignment;
3556 offset = (size + alignment - 1) & -alignment;
3561 if (warning.padded) {
3562 warningf(&compound->base.source_position, "'%T' needs padding", type);
3565 if (compound->modifiers & DM_PACKED && warning.packed) {
3566 warningf(&compound->base.source_position,
3567 "superfluous packed attribute on '%T'", type);
3571 type->base.size = offset;
3572 type->base.alignment = alignment;
3576 * Finish the construction of an union type by calculating
3577 * its size and alignment.
3579 static void finish_union_type(compound_type_t *type)
3581 assert(type->compound != NULL);
3583 compound_t *compound = type->compound;
3584 if (! compound->complete)
3588 il_alignment_t alignment = 1;
3590 entity_t *entry = compound->members.entities;
3591 for (; entry != NULL; entry = entry->base.next) {
3592 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3595 type_t *m_type = skip_typeref(entry->declaration.type);
3596 if (! is_type_valid(m_type))
3599 entry->compound_member.offset = 0;
3600 if (m_type->base.size > size)
3601 size = m_type->base.size;
3602 if (m_type->base.alignment > alignment)
3603 alignment = m_type->base.alignment;
3605 if (type->base.alignment != 0) {
3606 alignment = type->base.alignment;
3608 size = (size + alignment - 1) & -alignment;
3609 type->base.size = size;
3610 type->base.alignment = alignment;
3613 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3615 type_t *type = NULL;
3616 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3617 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3618 unsigned type_specifiers = 0;
3619 bool newtype = false;
3620 bool saw_error = false;
3621 bool old_gcc_extension = in_gcc_extension;
3623 specifiers->source_position = token.source_position;
3626 specifiers->modifiers
3627 |= parse_attributes(&specifiers->gnu_attributes);
3628 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3629 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3631 switch (token.type) {
3633 #define MATCH_STORAGE_CLASS(token, class) \
3635 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3636 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3638 specifiers->storage_class = class; \
3639 if (specifiers->thread_local) \
3640 goto check_thread_storage_class; \
3644 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3645 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3646 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3647 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3648 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3653 add_anchor_token(')');
3654 parse_microsoft_extended_decl_modifier(specifiers);
3655 rem_anchor_token(')');
3660 if (specifiers->thread_local) {
3661 errorf(HERE, "duplicate '__thread'");
3663 specifiers->thread_local = true;
3664 check_thread_storage_class:
3665 switch (specifiers->storage_class) {
3666 case STORAGE_CLASS_EXTERN:
3667 case STORAGE_CLASS_NONE:
3668 case STORAGE_CLASS_STATIC:
3672 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3673 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3674 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3675 wrong_thread_stoarge_class:
3676 errorf(HERE, "'__thread' used with '%s'", wrong);
3683 /* type qualifiers */
3684 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3686 qualifiers |= qualifier; \
3690 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3691 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3692 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3693 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3694 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3695 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3696 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3697 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3699 case T___extension__:
3701 in_gcc_extension = true;
3704 /* type specifiers */
3705 #define MATCH_SPECIFIER(token, specifier, name) \
3707 if (type_specifiers & specifier) { \
3708 errorf(HERE, "multiple " name " type specifiers given"); \
3710 type_specifiers |= specifier; \
3715 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3716 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3717 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3718 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3719 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3720 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3721 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3722 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3723 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3724 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3725 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3726 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3727 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3728 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3729 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3730 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3731 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3733 case T__forceinline:
3734 /* only in microsoft mode */
3735 specifiers->modifiers |= DM_FORCEINLINE;
3740 specifiers->is_inline = true;
3744 if (type_specifiers & SPECIFIER_LONG_LONG) {
3745 errorf(HERE, "multiple type specifiers given");
3746 } else if (type_specifiers & SPECIFIER_LONG) {
3747 type_specifiers |= SPECIFIER_LONG_LONG;
3749 type_specifiers |= SPECIFIER_LONG;
3755 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3757 type->compound.compound = parse_compound_type_specifier(true);
3758 finish_struct_type(&type->compound);
3762 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3763 type->compound.compound = parse_compound_type_specifier(false);
3764 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3765 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3766 finish_union_type(&type->compound);
3770 type = parse_enum_specifier();
3773 type = parse_typeof();
3775 case T___builtin_va_list:
3776 type = duplicate_type(type_valist);
3780 case T_IDENTIFIER: {
3781 /* only parse identifier if we haven't found a type yet */
3782 if (type != NULL || type_specifiers != 0) {
3783 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3784 * declaration, so it doesn't generate errors about expecting '(' or
3786 switch (look_ahead(1)->type) {
3793 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3797 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3802 goto finish_specifiers;
3806 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3807 if (typedef_type == NULL) {
3808 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3809 * declaration, so it doesn't generate 'implicit int' followed by more
3810 * errors later on. */
3811 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3817 errorf(HERE, "%K does not name a type", &token);
3820 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3822 type = allocate_type_zero(TYPE_TYPEDEF);
3823 type->typedeft.typedefe = &entity->typedefe;
3827 if (la1_type == '&' || la1_type == '*')
3828 goto finish_specifiers;
3833 goto finish_specifiers;
3838 type = typedef_type;
3842 /* function specifier */
3844 goto finish_specifiers;
3849 in_gcc_extension = old_gcc_extension;
3851 if (type == NULL || (saw_error && type_specifiers != 0)) {
3852 atomic_type_kind_t atomic_type;
3854 /* match valid basic types */
3855 switch (type_specifiers) {
3856 case SPECIFIER_VOID:
3857 atomic_type = ATOMIC_TYPE_VOID;
3859 case SPECIFIER_CHAR:
3860 atomic_type = ATOMIC_TYPE_CHAR;
3862 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3863 atomic_type = ATOMIC_TYPE_SCHAR;
3865 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3866 atomic_type = ATOMIC_TYPE_UCHAR;
3868 case SPECIFIER_SHORT:
3869 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3870 case SPECIFIER_SHORT | SPECIFIER_INT:
3871 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3872 atomic_type = ATOMIC_TYPE_SHORT;
3874 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3875 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3876 atomic_type = ATOMIC_TYPE_USHORT;
3879 case SPECIFIER_SIGNED:
3880 case SPECIFIER_SIGNED | SPECIFIER_INT:
3881 atomic_type = ATOMIC_TYPE_INT;
3883 case SPECIFIER_UNSIGNED:
3884 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3885 atomic_type = ATOMIC_TYPE_UINT;
3887 case SPECIFIER_LONG:
3888 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3889 case SPECIFIER_LONG | SPECIFIER_INT:
3890 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3891 atomic_type = ATOMIC_TYPE_LONG;
3893 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3894 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3895 atomic_type = ATOMIC_TYPE_ULONG;
3898 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3899 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3900 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3901 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3903 atomic_type = ATOMIC_TYPE_LONGLONG;
3904 goto warn_about_long_long;
3906 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3907 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3909 atomic_type = ATOMIC_TYPE_ULONGLONG;
3910 warn_about_long_long:
3911 if (warning.long_long) {
3912 warningf(&specifiers->source_position,
3913 "ISO C90 does not support 'long long'");
3917 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3918 atomic_type = unsigned_int8_type_kind;
3921 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3922 atomic_type = unsigned_int16_type_kind;
3925 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3926 atomic_type = unsigned_int32_type_kind;
3929 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3930 atomic_type = unsigned_int64_type_kind;
3933 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3934 atomic_type = unsigned_int128_type_kind;
3937 case SPECIFIER_INT8:
3938 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3939 atomic_type = int8_type_kind;
3942 case SPECIFIER_INT16:
3943 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3944 atomic_type = int16_type_kind;
3947 case SPECIFIER_INT32:
3948 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3949 atomic_type = int32_type_kind;
3952 case SPECIFIER_INT64:
3953 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3954 atomic_type = int64_type_kind;
3957 case SPECIFIER_INT128:
3958 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3959 atomic_type = int128_type_kind;
3962 case SPECIFIER_FLOAT:
3963 atomic_type = ATOMIC_TYPE_FLOAT;
3965 case SPECIFIER_DOUBLE:
3966 atomic_type = ATOMIC_TYPE_DOUBLE;
3968 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3969 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3971 case SPECIFIER_BOOL:
3972 atomic_type = ATOMIC_TYPE_BOOL;
3974 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3975 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3976 atomic_type = ATOMIC_TYPE_FLOAT;
3978 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3979 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3980 atomic_type = ATOMIC_TYPE_DOUBLE;
3982 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3983 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3984 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3987 /* invalid specifier combination, give an error message */
3988 if (type_specifiers == 0) {
3992 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3993 if (!(c_mode & _CXX) && !strict_mode) {
3994 if (warning.implicit_int) {
3995 warningf(HERE, "no type specifiers in declaration, using 'int'");
3997 atomic_type = ATOMIC_TYPE_INT;
4000 errorf(HERE, "no type specifiers given in declaration");
4002 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
4003 (type_specifiers & SPECIFIER_UNSIGNED)) {
4004 errorf(HERE, "signed and unsigned specifiers given");
4005 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
4006 errorf(HERE, "only integer types can be signed or unsigned");
4008 errorf(HERE, "multiple datatypes in declaration");
4013 if (type_specifiers & SPECIFIER_COMPLEX) {
4014 type = allocate_type_zero(TYPE_COMPLEX);
4015 type->complex.akind = atomic_type;
4016 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
4017 type = allocate_type_zero(TYPE_IMAGINARY);
4018 type->imaginary.akind = atomic_type;
4020 type = allocate_type_zero(TYPE_ATOMIC);
4021 type->atomic.akind = atomic_type;
4024 } else if (type_specifiers != 0) {
4025 errorf(HERE, "multiple datatypes in declaration");
4028 /* FIXME: check type qualifiers here */
4030 type->base.qualifiers = qualifiers;
4031 type->base.modifiers = modifiers;
4033 type_t *result = typehash_insert(type);
4034 if (newtype && result != type) {
4038 specifiers->type = result;
4042 specifiers->type = type_error_type;
4046 static type_qualifiers_t parse_type_qualifiers(void)
4048 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
4051 switch (token.type) {
4052 /* type qualifiers */
4053 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
4054 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
4055 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
4056 /* microsoft extended type modifiers */
4057 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
4058 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
4059 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4060 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4061 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4070 * Parses an K&R identifier list
4072 static void parse_identifier_list(scope_t *scope)
4075 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
4076 entity->base.source_position = token.source_position;
4077 entity->base.namespc = NAMESPACE_NORMAL;
4078 entity->base.symbol = token.v.symbol;
4079 /* a K&R parameter has no type, yet */
4082 append_entity(scope, entity);
4084 if (token.type != ',') {
4088 } while (token.type == T_IDENTIFIER);
4091 static entity_t *parse_parameter(void)
4093 declaration_specifiers_t specifiers;
4094 memset(&specifiers, 0, sizeof(specifiers));
4096 parse_declaration_specifiers(&specifiers);
4098 entity_t *entity = parse_declarator(&specifiers,
4099 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4100 anonymous_entity = NULL;
4104 static void semantic_parameter_incomplete(const entity_t *entity)
4106 assert(entity->kind == ENTITY_PARAMETER);
4108 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
4109 * list in a function declarator that is part of a
4110 * definition of that function shall not have
4111 * incomplete type. */
4112 type_t *type = skip_typeref(entity->declaration.type);
4113 if (is_type_incomplete(type)) {
4114 errorf(&entity->base.source_position,
4115 "parameter '%Y' has incomplete type '%T'", entity->base.symbol,
4116 entity->declaration.type);
4121 * Parses function type parameters (and optionally creates variable_t entities
4122 * for them in a scope)
4124 static void parse_parameters(function_type_t *type, scope_t *scope)
4127 add_anchor_token(')');
4128 int saved_comma_state = save_and_reset_anchor_state(',');
4130 if (token.type == T_IDENTIFIER &&
4131 !is_typedef_symbol(token.v.symbol)) {
4132 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4133 if (la1_type == ',' || la1_type == ')') {
4134 type->kr_style_parameters = true;
4135 parse_identifier_list(scope);
4136 goto parameters_finished;
4140 if (token.type == ')') {
4141 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4142 if (!(c_mode & _CXX))
4143 type->unspecified_parameters = true;
4144 goto parameters_finished;
4147 function_parameter_t *parameter;
4148 function_parameter_t *last_parameter = NULL;
4151 switch (token.type) {
4154 type->variadic = true;
4155 goto parameters_finished;
4158 case T___extension__:
4161 entity_t *entity = parse_parameter();
4162 if (entity->kind == ENTITY_TYPEDEF) {
4163 errorf(&entity->base.source_position,
4164 "typedef not allowed as function parameter");
4167 assert(is_declaration(entity));
4169 /* func(void) is not a parameter */
4170 if (last_parameter == NULL
4171 && token.type == ')'
4172 && entity->base.symbol == NULL
4173 && skip_typeref(entity->declaration.type) == type_void) {
4174 goto parameters_finished;
4176 semantic_parameter_incomplete(entity);
4178 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4179 memset(parameter, 0, sizeof(parameter[0]));
4180 parameter->type = entity->declaration.type;
4182 if (scope != NULL) {
4183 append_entity(scope, entity);
4186 if (last_parameter != NULL) {
4187 last_parameter->next = parameter;
4189 type->parameters = parameter;
4191 last_parameter = parameter;
4196 goto parameters_finished;
4198 if (token.type != ',') {
4199 goto parameters_finished;
4205 parameters_finished:
4206 rem_anchor_token(')');
4210 restore_anchor_state(',', saved_comma_state);
4213 typedef enum construct_type_kind_t {
4216 CONSTRUCT_REFERENCE,
4219 } construct_type_kind_t;
4221 typedef struct construct_type_t construct_type_t;
4222 struct construct_type_t {
4223 construct_type_kind_t kind;
4224 construct_type_t *next;
4227 typedef struct parsed_pointer_t parsed_pointer_t;
4228 struct parsed_pointer_t {
4229 construct_type_t construct_type;
4230 type_qualifiers_t type_qualifiers;
4231 variable_t *base_variable; /**< MS __based extension. */
4234 typedef struct parsed_reference_t parsed_reference_t;
4235 struct parsed_reference_t {
4236 construct_type_t construct_type;
4239 typedef struct construct_function_type_t construct_function_type_t;
4240 struct construct_function_type_t {
4241 construct_type_t construct_type;
4242 type_t *function_type;
4245 typedef struct parsed_array_t parsed_array_t;
4246 struct parsed_array_t {
4247 construct_type_t construct_type;
4248 type_qualifiers_t type_qualifiers;
4254 typedef struct construct_base_type_t construct_base_type_t;
4255 struct construct_base_type_t {
4256 construct_type_t construct_type;
4260 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4264 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4265 memset(pointer, 0, sizeof(pointer[0]));
4266 pointer->construct_type.kind = CONSTRUCT_POINTER;
4267 pointer->type_qualifiers = parse_type_qualifiers();
4268 pointer->base_variable = base_variable;
4270 return &pointer->construct_type;
4273 static construct_type_t *parse_reference_declarator(void)
4277 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4278 memset(reference, 0, sizeof(reference[0]));
4279 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4281 return (construct_type_t*)reference;
4284 static construct_type_t *parse_array_declarator(void)
4287 add_anchor_token(']');
4289 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4290 memset(array, 0, sizeof(array[0]));
4291 array->construct_type.kind = CONSTRUCT_ARRAY;
4293 if (token.type == T_static) {
4294 array->is_static = true;
4298 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4299 if (type_qualifiers != 0) {
4300 if (token.type == T_static) {
4301 array->is_static = true;
4305 array->type_qualifiers = type_qualifiers;
4307 if (token.type == '*' && look_ahead(1)->type == ']') {
4308 array->is_variable = true;
4310 } else if (token.type != ']') {
4311 array->size = parse_assignment_expression();
4314 rem_anchor_token(']');
4318 return &array->construct_type;
4321 static construct_type_t *parse_function_declarator(scope_t *scope,
4322 decl_modifiers_t modifiers)
4324 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4325 function_type_t *ftype = &type->function;
4327 ftype->linkage = current_linkage;
4329 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4330 case DM_NONE: break;
4331 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4332 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4333 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4334 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4337 errorf(HERE, "multiple calling conventions in declaration");
4341 parse_parameters(ftype, scope);
4343 construct_function_type_t *construct_function_type =
4344 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4345 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4346 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4347 construct_function_type->function_type = type;
4349 return &construct_function_type->construct_type;
4352 typedef struct parse_declarator_env_t {
4353 decl_modifiers_t modifiers;
4355 source_position_t source_position;
4357 } parse_declarator_env_t;
4359 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4360 bool may_be_abstract)
4362 /* construct a single linked list of construct_type_t's which describe
4363 * how to construct the final declarator type */
4364 construct_type_t *first = NULL;
4365 construct_type_t *last = NULL;
4366 gnu_attribute_t *attributes = NULL;
4368 decl_modifiers_t modifiers = parse_attributes(&attributes);
4370 /* MS __based extension */
4371 based_spec_t base_spec;
4372 base_spec.base_variable = NULL;
4375 construct_type_t *type;
4376 switch (token.type) {
4378 if (!(c_mode & _CXX))
4379 errorf(HERE, "references are only available for C++");
4380 if (base_spec.base_variable != NULL && warning.other) {
4381 warningf(&base_spec.source_position,
4382 "__based does not precede a pointer operator, ignored");
4384 type = parse_reference_declarator();
4386 base_spec.base_variable = NULL;
4390 type = parse_pointer_declarator(base_spec.base_variable);
4392 base_spec.base_variable = NULL;
4398 add_anchor_token(')');
4399 parse_microsoft_based(&base_spec);
4400 rem_anchor_token(')');
4405 goto ptr_operator_end;
4416 /* TODO: find out if this is correct */
4417 modifiers |= parse_attributes(&attributes);
4420 if (base_spec.base_variable != NULL && warning.other) {
4421 warningf(&base_spec.source_position,
4422 "__based does not precede a pointer operator, ignored");
4426 modifiers |= env->modifiers;
4427 env->modifiers = modifiers;
4430 construct_type_t *inner_types = NULL;
4432 switch (token.type) {
4435 errorf(HERE, "no identifier expected in typename");
4437 env->symbol = token.v.symbol;
4438 env->source_position = token.source_position;
4444 add_anchor_token(')');
4445 inner_types = parse_inner_declarator(env, may_be_abstract);
4446 if (inner_types != NULL) {
4447 /* All later declarators only modify the return type */
4450 rem_anchor_token(')');
4454 if (may_be_abstract)
4456 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4461 construct_type_t *p = last;
4464 construct_type_t *type;
4465 switch (token.type) {
4467 scope_t *scope = NULL;
4469 scope = &env->parameters;
4471 type = parse_function_declarator(scope, modifiers);
4475 type = parse_array_declarator();
4478 goto declarator_finished;
4481 /* insert in the middle of the list (behind p) */
4483 type->next = p->next;
4494 declarator_finished:
4495 /* append inner_types at the end of the list, we don't to set last anymore
4496 * as it's not needed anymore */
4498 assert(first == NULL);
4499 first = inner_types;
4501 last->next = inner_types;
4509 static void parse_declaration_attributes(entity_t *entity)
4511 gnu_attribute_t *attributes = NULL;
4512 decl_modifiers_t modifiers = parse_attributes(&attributes);
4518 if (entity->kind == ENTITY_TYPEDEF) {
4519 modifiers |= entity->typedefe.modifiers;
4520 type = entity->typedefe.type;
4522 assert(is_declaration(entity));
4523 modifiers |= entity->declaration.modifiers;
4524 type = entity->declaration.type;
4529 /* handle these strange/stupid mode attributes */
4530 gnu_attribute_t *attribute = attributes;
4531 for ( ; attribute != NULL; attribute = attribute->next) {
4532 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4535 atomic_type_kind_t akind = attribute->u.akind;
4536 if (!is_type_signed(type)) {
4538 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4539 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4540 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4541 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4543 panic("invalid akind in mode attribute");
4547 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4548 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4549 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4550 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4552 panic("invalid akind in mode attribute");
4556 type = make_atomic_type(akind, type->base.qualifiers);
4559 type_modifiers_t type_modifiers = type->base.modifiers;
4560 if (modifiers & DM_TRANSPARENT_UNION)
4561 type_modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4563 if (type->base.modifiers != type_modifiers) {
4564 type_t *copy = duplicate_type(type);
4565 copy->base.modifiers = type_modifiers;
4567 type = typehash_insert(copy);
4569 obstack_free(type_obst, copy);
4573 if (entity->kind == ENTITY_TYPEDEF) {
4574 entity->typedefe.type = type;
4575 entity->typedefe.modifiers = modifiers;
4577 entity->declaration.type = type;
4578 entity->declaration.modifiers = modifiers;
4582 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4584 construct_type_t *iter = construct_list;
4585 for (; iter != NULL; iter = iter->next) {
4586 switch (iter->kind) {
4587 case CONSTRUCT_INVALID:
4588 internal_errorf(HERE, "invalid type construction found");
4589 case CONSTRUCT_FUNCTION: {
4590 construct_function_type_t *construct_function_type
4591 = (construct_function_type_t*) iter;
4593 type_t *function_type = construct_function_type->function_type;
4595 function_type->function.return_type = type;
4597 type_t *skipped_return_type = skip_typeref(type);
4599 if (is_type_function(skipped_return_type)) {
4600 errorf(HERE, "function returning function is not allowed");
4601 } else if (is_type_array(skipped_return_type)) {
4602 errorf(HERE, "function returning array is not allowed");
4604 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4606 "type qualifiers in return type of function type are meaningless");
4610 type = function_type;
4614 case CONSTRUCT_POINTER: {
4615 if (is_type_reference(skip_typeref(type)))
4616 errorf(HERE, "cannot declare a pointer to reference");
4618 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4619 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4623 case CONSTRUCT_REFERENCE:
4624 if (is_type_reference(skip_typeref(type)))
4625 errorf(HERE, "cannot declare a reference to reference");
4627 type = make_reference_type(type);
4630 case CONSTRUCT_ARRAY: {
4631 if (is_type_reference(skip_typeref(type)))
4632 errorf(HERE, "cannot declare an array of references");
4634 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4635 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4637 expression_t *size_expression = parsed_array->size;
4638 if (size_expression != NULL) {
4640 = create_implicit_cast(size_expression, type_size_t);
4643 array_type->base.qualifiers = parsed_array->type_qualifiers;
4644 array_type->array.element_type = type;
4645 array_type->array.is_static = parsed_array->is_static;
4646 array_type->array.is_variable = parsed_array->is_variable;
4647 array_type->array.size_expression = size_expression;
4649 if (size_expression != NULL) {
4650 if (is_constant_expression(size_expression)) {
4651 array_type->array.size_constant = true;
4652 array_type->array.size
4653 = fold_constant(size_expression);
4655 array_type->array.is_vla = true;
4659 type_t *skipped_type = skip_typeref(type);
4661 if (is_type_incomplete(skipped_type)) {
4662 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4663 } else if (is_type_function(skipped_type)) {
4664 errorf(HERE, "array of functions is not allowed");
4671 type_t *hashed_type = typehash_insert(type);
4672 if (hashed_type != type) {
4673 /* the function type was constructed earlier freeing it here will
4674 * destroy other types... */
4675 if (iter->kind != CONSTRUCT_FUNCTION) {
4685 static type_t *automatic_type_conversion(type_t *orig_type);
4687 static type_t *semantic_parameter(const source_position_t *pos,
4689 const declaration_specifiers_t *specifiers,
4692 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4693 * shall be adjusted to ``qualified pointer to type'',
4695 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4696 * type'' shall be adjusted to ``pointer to function
4697 * returning type'', as in 6.3.2.1. */
4698 type = automatic_type_conversion(type);
4700 if (specifiers->is_inline && is_type_valid(type)) {
4701 errorf(pos, "parameter '%Y' declared 'inline'", symbol);
4704 /* §6.9.1:6 The declarations in the declaration list shall contain
4705 * no storage-class specifier other than register and no
4706 * initializations. */
4707 if (specifiers->thread_local || (
4708 specifiers->storage_class != STORAGE_CLASS_NONE &&
4709 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4711 errorf(pos, "invalid storage class for parameter '%Y'", symbol);
4714 /* delay test for incomplete type, because we might have (void)
4715 * which is legal but incomplete... */
4720 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4721 declarator_flags_t flags)
4723 parse_declarator_env_t env;
4724 memset(&env, 0, sizeof(env));
4725 env.modifiers = specifiers->modifiers;
4727 construct_type_t *construct_type =
4728 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4730 construct_declarator_type(construct_type, specifiers->type);
4731 type_t *type = skip_typeref(orig_type);
4733 if (construct_type != NULL) {
4734 obstack_free(&temp_obst, construct_type);
4738 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4739 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4740 entity->base.symbol = env.symbol;
4741 entity->base.source_position = env.source_position;
4742 entity->typedefe.type = orig_type;
4744 if (anonymous_entity != NULL) {
4745 if (is_type_compound(type)) {
4746 assert(anonymous_entity->compound.alias == NULL);
4747 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4748 anonymous_entity->kind == ENTITY_UNION);
4749 anonymous_entity->compound.alias = entity;
4750 anonymous_entity = NULL;
4751 } else if (is_type_enum(type)) {
4752 assert(anonymous_entity->enume.alias == NULL);
4753 assert(anonymous_entity->kind == ENTITY_ENUM);
4754 anonymous_entity->enume.alias = entity;
4755 anonymous_entity = NULL;
4759 /* create a declaration type entity */
4760 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4761 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4763 if (specifiers->is_inline && is_type_valid(type)) {
4764 errorf(&env.source_position,
4765 "compound member '%Y' declared 'inline'", env.symbol);
4768 if (specifiers->thread_local ||
4769 specifiers->storage_class != STORAGE_CLASS_NONE) {
4770 errorf(&env.source_position,
4771 "compound member '%Y' must have no storage class",
4774 } else if (flags & DECL_IS_PARAMETER) {
4775 orig_type = semantic_parameter(&env.source_position, orig_type,
4776 specifiers, env.symbol);
4778 entity = allocate_entity_zero(ENTITY_PARAMETER);
4779 } else if (is_type_function(type)) {
4780 entity = allocate_entity_zero(ENTITY_FUNCTION);
4782 entity->function.is_inline = specifiers->is_inline;
4783 entity->function.parameters = env.parameters;
4785 if (specifiers->thread_local || (
4786 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4787 specifiers->storage_class != STORAGE_CLASS_NONE &&
4788 specifiers->storage_class != STORAGE_CLASS_STATIC)
4790 errorf(&env.source_position,
4791 "invalid storage class for function '%Y'", env.symbol);
4794 entity = allocate_entity_zero(ENTITY_VARIABLE);
4796 entity->variable.get_property_sym = specifiers->get_property_sym;
4797 entity->variable.put_property_sym = specifiers->put_property_sym;
4798 if (specifiers->alignment != 0) {
4799 /* TODO: add checks here */
4800 entity->variable.alignment = specifiers->alignment;
4803 if (specifiers->is_inline && is_type_valid(type)) {
4804 errorf(&env.source_position,
4805 "variable '%Y' declared 'inline'", env.symbol);
4808 entity->variable.thread_local = specifiers->thread_local;
4810 bool invalid_storage_class = false;
4811 if (current_scope == file_scope) {
4812 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4813 specifiers->storage_class != STORAGE_CLASS_NONE &&
4814 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4815 invalid_storage_class = true;
4818 if (specifiers->thread_local &&
4819 specifiers->storage_class == STORAGE_CLASS_NONE) {
4820 invalid_storage_class = true;
4823 if (invalid_storage_class) {
4824 errorf(&env.source_position,
4825 "invalid storage class for variable '%Y'", env.symbol);
4829 entity->base.source_position = env.source_position;
4830 entity->base.symbol = env.symbol;
4831 entity->base.namespc = NAMESPACE_NORMAL;
4832 entity->declaration.type = orig_type;
4833 entity->declaration.modifiers = env.modifiers;
4834 entity->declaration.deprecated_string = specifiers->deprecated_string;
4836 storage_class_t storage_class = specifiers->storage_class;
4837 entity->declaration.declared_storage_class = storage_class;
4839 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4840 storage_class = STORAGE_CLASS_AUTO;
4841 entity->declaration.storage_class = storage_class;
4844 parse_declaration_attributes(entity);
4849 static type_t *parse_abstract_declarator(type_t *base_type)
4851 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4853 type_t *result = construct_declarator_type(construct_type, base_type);
4854 if (construct_type != NULL) {
4855 obstack_free(&temp_obst, construct_type);
4862 * Check if the declaration of main is suspicious. main should be a
4863 * function with external linkage, returning int, taking either zero
4864 * arguments, two, or three arguments of appropriate types, ie.
4866 * int main([ int argc, char **argv [, char **env ] ]).
4868 * @param decl the declaration to check
4869 * @param type the function type of the declaration
4871 static void check_type_of_main(const entity_t *entity)
4873 const source_position_t *pos = &entity->base.source_position;
4874 if (entity->kind != ENTITY_FUNCTION) {
4875 warningf(pos, "'main' is not a function");
4879 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4880 warningf(pos, "'main' is normally a non-static function");
4883 type_t *type = skip_typeref(entity->declaration.type);
4884 assert(is_type_function(type));
4886 function_type_t *func_type = &type->function;
4887 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4888 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4889 func_type->return_type);
4891 const function_parameter_t *parm = func_type->parameters;
4893 type_t *const first_type = parm->type;
4894 if (!types_compatible(skip_typeref(first_type), type_int)) {
4896 "first argument of 'main' should be 'int', but is '%T'",
4901 type_t *const second_type = parm->type;
4902 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4903 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4907 type_t *const third_type = parm->type;
4908 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4909 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4913 goto warn_arg_count;
4917 warningf(pos, "'main' takes only zero, two or three arguments");
4923 * Check if a symbol is the equal to "main".
4925 static bool is_sym_main(const symbol_t *const sym)
4927 return strcmp(sym->string, "main") == 0;
4930 static void error_redefined_as_different_kind(const source_position_t *pos,
4931 const entity_t *old, entity_kind_t new_kind)
4933 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4934 get_entity_kind_name(old->kind), old->base.symbol,
4935 get_entity_kind_name(new_kind), &old->base.source_position);
4939 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4940 * for various problems that occur for multiple definitions
4942 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4944 const symbol_t *const symbol = entity->base.symbol;
4945 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4946 const source_position_t *pos = &entity->base.source_position;
4948 /* can happen in error cases */
4952 entity_t *previous_entity = get_entity(symbol, namespc);
4953 /* pushing the same entity twice will break the stack structure */
4954 assert(previous_entity != entity);
4956 if (entity->kind == ENTITY_FUNCTION) {
4957 type_t *const orig_type = entity->declaration.type;
4958 type_t *const type = skip_typeref(orig_type);
4960 assert(is_type_function(type));
4961 if (type->function.unspecified_parameters &&
4962 warning.strict_prototypes &&
4963 previous_entity == NULL) {
4964 warningf(pos, "function declaration '%#T' is not a prototype",
4968 if (warning.main && current_scope == file_scope
4969 && is_sym_main(symbol)) {
4970 check_type_of_main(entity);
4974 if (is_declaration(entity) &&
4975 warning.nested_externs &&
4976 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4977 current_scope != file_scope) {
4978 warningf(pos, "nested extern declaration of '%#T'",
4979 entity->declaration.type, symbol);
4982 if (previous_entity != NULL &&
4983 previous_entity->base.parent_scope == ¤t_function->parameters &&
4984 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4985 assert(previous_entity->kind == ENTITY_PARAMETER);
4987 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4988 entity->declaration.type, symbol,
4989 previous_entity->declaration.type, symbol,
4990 &previous_entity->base.source_position);
4994 if (previous_entity != NULL &&
4995 previous_entity->base.parent_scope == current_scope) {
4996 if (previous_entity->kind != entity->kind) {
4997 error_redefined_as_different_kind(pos, previous_entity,
5001 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
5002 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
5003 symbol, &previous_entity->base.source_position);
5006 if (previous_entity->kind == ENTITY_TYPEDEF) {
5007 /* TODO: C++ allows this for exactly the same type */
5008 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
5009 symbol, &previous_entity->base.source_position);
5013 /* at this point we should have only VARIABLES or FUNCTIONS */
5014 assert(is_declaration(previous_entity) && is_declaration(entity));
5016 declaration_t *const prev_decl = &previous_entity->declaration;
5017 declaration_t *const decl = &entity->declaration;
5019 /* can happen for K&R style declarations */
5020 if (prev_decl->type == NULL &&
5021 previous_entity->kind == ENTITY_PARAMETER &&
5022 entity->kind == ENTITY_PARAMETER) {
5023 prev_decl->type = decl->type;
5024 prev_decl->storage_class = decl->storage_class;
5025 prev_decl->declared_storage_class = decl->declared_storage_class;
5026 prev_decl->modifiers = decl->modifiers;
5027 prev_decl->deprecated_string = decl->deprecated_string;
5028 return previous_entity;
5031 type_t *const orig_type = decl->type;
5032 assert(orig_type != NULL);
5033 type_t *const type = skip_typeref(orig_type);
5034 type_t * prev_type = skip_typeref(prev_decl->type);
5036 if (!types_compatible(type, prev_type)) {
5038 "declaration '%#T' is incompatible with '%#T' (declared %P)",
5039 orig_type, symbol, prev_decl->type, symbol,
5040 &previous_entity->base.source_position);
5042 unsigned old_storage_class = prev_decl->storage_class;
5043 if (warning.redundant_decls &&
5046 !(prev_decl->modifiers & DM_USED) &&
5047 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
5048 warningf(&previous_entity->base.source_position,
5049 "unnecessary static forward declaration for '%#T'",
5050 prev_decl->type, symbol);
5053 unsigned new_storage_class = decl->storage_class;
5054 if (is_type_incomplete(prev_type)) {
5055 prev_decl->type = type;
5059 /* pretend no storage class means extern for function
5060 * declarations (except if the previous declaration is neither
5061 * none nor extern) */
5062 if (entity->kind == ENTITY_FUNCTION) {
5063 if (prev_type->function.unspecified_parameters) {
5064 prev_decl->type = type;
5068 switch (old_storage_class) {
5069 case STORAGE_CLASS_NONE:
5070 old_storage_class = STORAGE_CLASS_EXTERN;
5073 case STORAGE_CLASS_EXTERN:
5074 if (is_definition) {
5075 if (warning.missing_prototypes &&
5076 prev_type->function.unspecified_parameters &&
5077 !is_sym_main(symbol)) {
5078 warningf(pos, "no previous prototype for '%#T'",
5081 } else if (new_storage_class == STORAGE_CLASS_NONE) {
5082 new_storage_class = STORAGE_CLASS_EXTERN;
5091 if (old_storage_class == STORAGE_CLASS_EXTERN &&
5092 new_storage_class == STORAGE_CLASS_EXTERN) {
5093 warn_redundant_declaration:
5094 if (!is_definition &&
5095 warning.redundant_decls &&
5096 is_type_valid(prev_type) &&
5097 strcmp(previous_entity->base.source_position.input_name,
5098 "<builtin>") != 0) {
5100 "redundant declaration for '%Y' (declared %P)",
5101 symbol, &previous_entity->base.source_position);
5103 } else if (current_function == NULL) {
5104 if (old_storage_class != STORAGE_CLASS_STATIC &&
5105 new_storage_class == STORAGE_CLASS_STATIC) {
5107 "static declaration of '%Y' follows non-static declaration (declared %P)",
5108 symbol, &previous_entity->base.source_position);
5109 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5110 prev_decl->storage_class = STORAGE_CLASS_NONE;
5111 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
5113 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5115 goto error_redeclaration;
5116 goto warn_redundant_declaration;
5118 } else if (is_type_valid(prev_type)) {
5119 if (old_storage_class == new_storage_class) {
5120 error_redeclaration:
5121 errorf(pos, "redeclaration of '%Y' (declared %P)",
5122 symbol, &previous_entity->base.source_position);
5125 "redeclaration of '%Y' with different linkage (declared %P)",
5126 symbol, &previous_entity->base.source_position);
5131 prev_decl->modifiers |= decl->modifiers;
5132 if (entity->kind == ENTITY_FUNCTION) {
5133 previous_entity->function.is_inline |= entity->function.is_inline;
5135 return previous_entity;
5138 if (entity->kind == ENTITY_FUNCTION) {
5139 if (is_definition &&
5140 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5141 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5142 warningf(pos, "no previous prototype for '%#T'",
5143 entity->declaration.type, symbol);
5144 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5145 warningf(pos, "no previous declaration for '%#T'",
5146 entity->declaration.type, symbol);
5149 } else if (warning.missing_declarations &&
5150 entity->kind == ENTITY_VARIABLE &&
5151 current_scope == file_scope) {
5152 declaration_t *declaration = &entity->declaration;
5153 if (declaration->storage_class == STORAGE_CLASS_NONE) {
5154 warningf(pos, "no previous declaration for '%#T'",
5155 declaration->type, symbol);
5160 assert(entity->base.parent_scope == NULL);
5161 assert(current_scope != NULL);
5163 entity->base.parent_scope = current_scope;
5164 entity->base.namespc = NAMESPACE_NORMAL;
5165 environment_push(entity);
5166 append_entity(current_scope, entity);
5171 static void parser_error_multiple_definition(entity_t *entity,
5172 const source_position_t *source_position)
5174 errorf(source_position, "multiple definition of '%Y' (declared %P)",
5175 entity->base.symbol, &entity->base.source_position);
5178 static bool is_declaration_specifier(const token_t *token,
5179 bool only_specifiers_qualifiers)
5181 switch (token->type) {
5186 return is_typedef_symbol(token->v.symbol);
5188 case T___extension__:
5190 return !only_specifiers_qualifiers;
5197 static void parse_init_declarator_rest(entity_t *entity)
5199 assert(is_declaration(entity));
5200 declaration_t *const declaration = &entity->declaration;
5204 type_t *orig_type = declaration->type;
5205 type_t *type = skip_typeref(orig_type);
5207 if (entity->kind == ENTITY_VARIABLE
5208 && entity->variable.initializer != NULL) {
5209 parser_error_multiple_definition(entity, HERE);
5212 bool must_be_constant = false;
5213 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5214 entity->base.parent_scope == file_scope) {
5215 must_be_constant = true;
5218 if (is_type_function(type)) {
5219 errorf(&entity->base.source_position,
5220 "function '%#T' is initialized like a variable",
5221 orig_type, entity->base.symbol);
5222 orig_type = type_error_type;
5225 parse_initializer_env_t env;
5226 env.type = orig_type;
5227 env.must_be_constant = must_be_constant;
5228 env.entity = entity;
5229 current_init_decl = entity;
5231 initializer_t *initializer = parse_initializer(&env);
5232 current_init_decl = NULL;
5234 if (entity->kind == ENTITY_VARIABLE) {
5235 /* § 6.7.5 (22) array initializers for arrays with unknown size
5236 * determine the array type size */
5237 declaration->type = env.type;
5238 entity->variable.initializer = initializer;
5242 /* parse rest of a declaration without any declarator */
5243 static void parse_anonymous_declaration_rest(
5244 const declaration_specifiers_t *specifiers)
5247 anonymous_entity = NULL;
5249 if (warning.other) {
5250 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
5251 specifiers->thread_local) {
5252 warningf(&specifiers->source_position,
5253 "useless storage class in empty declaration");
5256 type_t *type = specifiers->type;
5257 switch (type->kind) {
5258 case TYPE_COMPOUND_STRUCT:
5259 case TYPE_COMPOUND_UNION: {
5260 if (type->compound.compound->base.symbol == NULL) {
5261 warningf(&specifiers->source_position,
5262 "unnamed struct/union that defines no instances");
5271 warningf(&specifiers->source_position, "empty declaration");
5277 static void check_variable_type_complete(entity_t *ent)
5279 if (ent->kind != ENTITY_VARIABLE)
5282 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5283 * type for the object shall be complete [...] */
5284 declaration_t *decl = &ent->declaration;
5285 if (decl->storage_class != STORAGE_CLASS_NONE)
5288 type_t *const orig_type = decl->type;
5289 type_t *const type = skip_typeref(orig_type);
5290 if (!is_type_incomplete(type))
5293 /* GCC allows global arrays without size and assigns them a length of one,
5294 * if no different declaration follows */
5295 if (is_type_array(type) &&
5297 ent->base.parent_scope == file_scope) {
5298 ARR_APP1(declaration_t*, incomplete_arrays, decl);
5302 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5303 orig_type, ent->base.symbol);
5307 static void parse_declaration_rest(entity_t *ndeclaration,
5308 const declaration_specifiers_t *specifiers,
5309 parsed_declaration_func finished_declaration,
5310 declarator_flags_t flags)
5312 add_anchor_token(';');
5313 add_anchor_token(',');
5315 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5317 if (token.type == '=') {
5318 parse_init_declarator_rest(entity);
5319 } else if (entity->kind == ENTITY_VARIABLE) {
5320 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5321 * [...] where the extern specifier is explicitly used. */
5322 declaration_t *decl = &entity->declaration;
5323 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5324 type_t *type = decl->type;
5325 if (is_type_reference(skip_typeref(type))) {
5326 errorf(&entity->base.source_position,
5327 "reference '%#T' must be initialized",
5328 type, entity->base.symbol);
5333 check_variable_type_complete(entity);
5335 if (token.type != ',')
5339 add_anchor_token('=');
5340 ndeclaration = parse_declarator(specifiers, flags);
5341 rem_anchor_token('=');
5346 anonymous_entity = NULL;
5347 rem_anchor_token(';');
5348 rem_anchor_token(',');
5351 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5353 symbol_t *symbol = entity->base.symbol;
5354 if (symbol == NULL) {
5355 errorf(HERE, "anonymous declaration not valid as function parameter");
5359 assert(entity->base.namespc == NAMESPACE_NORMAL);
5360 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5361 if (previous_entity == NULL
5362 || previous_entity->base.parent_scope != current_scope) {
5363 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5368 if (is_definition) {
5369 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
5372 return record_entity(entity, false);
5375 static void parse_declaration(parsed_declaration_func finished_declaration,
5376 declarator_flags_t flags)
5378 declaration_specifiers_t specifiers;
5379 memset(&specifiers, 0, sizeof(specifiers));
5381 add_anchor_token(';');
5382 parse_declaration_specifiers(&specifiers);
5383 rem_anchor_token(';');
5385 if (token.type == ';') {
5386 parse_anonymous_declaration_rest(&specifiers);
5388 entity_t *entity = parse_declarator(&specifiers, flags);
5389 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
5393 static type_t *get_default_promoted_type(type_t *orig_type)
5395 type_t *result = orig_type;
5397 type_t *type = skip_typeref(orig_type);
5398 if (is_type_integer(type)) {
5399 result = promote_integer(type);
5400 } else if (type == type_float) {
5401 result = type_double;
5407 static void parse_kr_declaration_list(entity_t *entity)
5409 if (entity->kind != ENTITY_FUNCTION)
5412 type_t *type = skip_typeref(entity->declaration.type);
5413 assert(is_type_function(type));
5414 if (!type->function.kr_style_parameters)
5418 add_anchor_token('{');
5420 /* push function parameters */
5421 size_t const top = environment_top();
5422 scope_t *old_scope = scope_push(&entity->function.parameters);
5424 entity_t *parameter = entity->function.parameters.entities;
5425 for ( ; parameter != NULL; parameter = parameter->base.next) {
5426 assert(parameter->base.parent_scope == NULL);
5427 parameter->base.parent_scope = current_scope;
5428 environment_push(parameter);
5431 /* parse declaration list */
5433 switch (token.type) {
5435 case T___extension__:
5436 /* This covers symbols, which are no type, too, and results in
5437 * better error messages. The typical cases are misspelled type
5438 * names and missing includes. */
5440 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
5448 /* pop function parameters */
5449 assert(current_scope == &entity->function.parameters);
5450 scope_pop(old_scope);
5451 environment_pop_to(top);
5453 /* update function type */
5454 type_t *new_type = duplicate_type(type);
5456 function_parameter_t *parameters = NULL;
5457 function_parameter_t *last_parameter = NULL;
5459 parameter = entity->function.parameters.entities;
5460 for (; parameter != NULL; parameter = parameter->base.next) {
5461 type_t *parameter_type = parameter->declaration.type;
5462 if (parameter_type == NULL) {
5464 errorf(HERE, "no type specified for function parameter '%Y'",
5465 parameter->base.symbol);
5467 if (warning.implicit_int) {
5468 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5469 parameter->base.symbol);
5471 parameter_type = type_int;
5472 parameter->declaration.type = parameter_type;
5476 semantic_parameter_incomplete(parameter);
5477 parameter_type = parameter->declaration.type;
5480 * we need the default promoted types for the function type
5482 parameter_type = get_default_promoted_type(parameter_type);
5484 function_parameter_t *function_parameter
5485 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5486 memset(function_parameter, 0, sizeof(function_parameter[0]));
5488 function_parameter->type = parameter_type;
5489 if (last_parameter != NULL) {
5490 last_parameter->next = function_parameter;
5492 parameters = function_parameter;
5494 last_parameter = function_parameter;
5497 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5499 new_type->function.parameters = parameters;
5500 new_type->function.unspecified_parameters = true;
5502 type = typehash_insert(new_type);
5503 if (type != new_type) {
5504 obstack_free(type_obst, new_type);
5507 entity->declaration.type = type;
5509 rem_anchor_token('{');
5512 static bool first_err = true;
5515 * When called with first_err set, prints the name of the current function,
5518 static void print_in_function(void)
5522 diagnosticf("%s: In function '%Y':\n",
5523 current_function->base.base.source_position.input_name,
5524 current_function->base.base.symbol);
5529 * Check if all labels are defined in the current function.
5530 * Check if all labels are used in the current function.
5532 static void check_labels(void)
5534 for (const goto_statement_t *goto_statement = goto_first;
5535 goto_statement != NULL;
5536 goto_statement = goto_statement->next) {
5537 /* skip computed gotos */
5538 if (goto_statement->expression != NULL)
5541 label_t *label = goto_statement->label;
5544 if (label->base.source_position.input_name == NULL) {
5545 print_in_function();
5546 errorf(&goto_statement->base.source_position,
5547 "label '%Y' used but not defined", label->base.symbol);
5551 if (warning.unused_label) {
5552 for (const label_statement_t *label_statement = label_first;
5553 label_statement != NULL;
5554 label_statement = label_statement->next) {
5555 label_t *label = label_statement->label;
5557 if (! label->used) {
5558 print_in_function();
5559 warningf(&label_statement->base.source_position,
5560 "label '%Y' defined but not used", label->base.symbol);
5566 static void warn_unused_entity(entity_t *entity, entity_t *end)
5568 for (; entity != NULL; entity = entity->base.next) {
5569 if (!is_declaration(entity))
5572 declaration_t *declaration = &entity->declaration;
5573 if (declaration->implicit)
5576 if (!declaration->used) {
5577 print_in_function();
5578 const char *what = get_entity_kind_name(entity->kind);
5579 warningf(&entity->base.source_position, "%s '%Y' is unused",
5580 what, entity->base.symbol);
5581 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5582 print_in_function();
5583 const char *what = get_entity_kind_name(entity->kind);
5584 warningf(&entity->base.source_position, "%s '%Y' is never read",
5585 what, entity->base.symbol);
5593 static void check_unused_variables(statement_t *const stmt, void *const env)
5597 switch (stmt->kind) {
5598 case STATEMENT_DECLARATION: {
5599 declaration_statement_t const *const decls = &stmt->declaration;
5600 warn_unused_entity(decls->declarations_begin,
5601 decls->declarations_end);
5606 warn_unused_entity(stmt->fors.scope.entities, NULL);
5615 * Check declarations of current_function for unused entities.
5617 static void check_declarations(void)
5619 if (warning.unused_parameter) {
5620 const scope_t *scope = ¤t_function->parameters;
5622 /* do not issue unused warnings for main */
5623 if (!is_sym_main(current_function->base.base.symbol)) {
5624 warn_unused_entity(scope->entities, NULL);
5627 if (warning.unused_variable) {
5628 walk_statements(current_function->statement, check_unused_variables,
5633 static int determine_truth(expression_t const* const cond)
5636 !is_constant_expression(cond) ? 0 :
5637 fold_constant(cond) != 0 ? 1 :
5641 static void check_reachable(statement_t *);
5643 static bool expression_returns(expression_t const *const expr)
5645 switch (expr->kind) {
5647 expression_t const *const func = expr->call.function;
5648 if (func->kind == EXPR_REFERENCE) {
5649 entity_t *entity = func->reference.entity;
5650 if (entity->kind == ENTITY_FUNCTION
5651 && entity->declaration.modifiers & DM_NORETURN)
5655 if (!expression_returns(func))
5658 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5659 if (!expression_returns(arg->expression))
5666 case EXPR_REFERENCE:
5667 case EXPR_REFERENCE_ENUM_VALUE:
5669 case EXPR_CHARACTER_CONSTANT:
5670 case EXPR_WIDE_CHARACTER_CONSTANT:
5671 case EXPR_STRING_LITERAL:
5672 case EXPR_WIDE_STRING_LITERAL:
5673 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5674 case EXPR_LABEL_ADDRESS:
5675 case EXPR_CLASSIFY_TYPE:
5676 case EXPR_SIZEOF: // TODO handle obscure VLA case
5679 case EXPR_BUILTIN_SYMBOL:
5680 case EXPR_BUILTIN_CONSTANT_P:
5681 case EXPR_BUILTIN_PREFETCH:
5686 case EXPR_STATEMENT:
5687 check_reachable(expr->statement.statement);
5688 // TODO check if statement can be left
5691 case EXPR_CONDITIONAL:
5692 // TODO handle constant expression
5694 if (!expression_returns(expr->conditional.condition))
5697 if (expr->conditional.true_expression != NULL
5698 && expression_returns(expr->conditional.true_expression))
5701 return expression_returns(expr->conditional.false_expression);
5704 return expression_returns(expr->select.compound);
5706 case EXPR_ARRAY_ACCESS:
5708 expression_returns(expr->array_access.array_ref) &&
5709 expression_returns(expr->array_access.index);
5712 return expression_returns(expr->va_starte.ap);
5715 return expression_returns(expr->va_arge.ap);
5717 EXPR_UNARY_CASES_MANDATORY
5718 return expression_returns(expr->unary.value);
5720 case EXPR_UNARY_THROW:
5724 // TODO handle constant lhs of && and ||
5726 expression_returns(expr->binary.left) &&
5727 expression_returns(expr->binary.right);
5733 panic("unhandled expression");
5736 static bool initializer_returns(initializer_t const *const init)
5738 switch (init->kind) {
5739 case INITIALIZER_VALUE:
5740 return expression_returns(init->value.value);
5742 case INITIALIZER_LIST: {
5743 initializer_t * const* i = init->list.initializers;
5744 initializer_t * const* const end = i + init->list.len;
5745 bool returns = true;
5746 for (; i != end; ++i) {
5747 if (!initializer_returns(*i))
5753 case INITIALIZER_STRING:
5754 case INITIALIZER_WIDE_STRING:
5755 case INITIALIZER_DESIGNATOR: // designators have no payload
5758 panic("unhandled initializer");
5761 static bool noreturn_candidate;
5763 static void check_reachable(statement_t *const stmt)
5765 if (stmt->base.reachable)
5767 if (stmt->kind != STATEMENT_DO_WHILE)
5768 stmt->base.reachable = true;
5770 statement_t *last = stmt;
5772 switch (stmt->kind) {
5773 case STATEMENT_INVALID:
5774 case STATEMENT_EMPTY:
5775 case STATEMENT_LOCAL_LABEL:
5777 next = stmt->base.next;
5780 case STATEMENT_DECLARATION: {
5781 declaration_statement_t const *const decl = &stmt->declaration;
5782 entity_t const * ent = decl->declarations_begin;
5783 entity_t const *const last = decl->declarations_end;
5785 for (;; ent = ent->base.next) {
5786 if (ent->kind == ENTITY_VARIABLE &&
5787 ent->variable.initializer != NULL &&
5788 !initializer_returns(ent->variable.initializer)) {
5795 next = stmt->base.next;
5799 case STATEMENT_COMPOUND:
5800 next = stmt->compound.statements;
5803 case STATEMENT_RETURN: {
5804 expression_t const *const val = stmt->returns.value;
5805 if (val == NULL || expression_returns(val))
5806 noreturn_candidate = false;
5810 case STATEMENT_IF: {
5811 if_statement_t const *const ifs = &stmt->ifs;
5812 expression_t const *const cond = ifs->condition;
5814 if (!expression_returns(cond))
5817 int const val = determine_truth(cond);
5820 check_reachable(ifs->true_statement);
5825 if (ifs->false_statement != NULL) {
5826 check_reachable(ifs->false_statement);
5830 next = stmt->base.next;
5834 case STATEMENT_SWITCH: {
5835 switch_statement_t const *const switchs = &stmt->switchs;
5836 expression_t const *const expr = switchs->expression;
5838 if (!expression_returns(expr))
5841 if (is_constant_expression(expr)) {
5842 long const val = fold_constant(expr);
5843 case_label_statement_t * defaults = NULL;
5844 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5845 if (i->expression == NULL) {
5850 if (i->first_case <= val && val <= i->last_case) {
5851 check_reachable((statement_t*)i);
5856 if (defaults != NULL) {
5857 check_reachable((statement_t*)defaults);
5861 bool has_default = false;
5862 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5863 if (i->expression == NULL)
5866 check_reachable((statement_t*)i);
5873 next = stmt->base.next;
5877 case STATEMENT_EXPRESSION: {
5878 /* Check for noreturn function call */
5879 expression_t const *const expr = stmt->expression.expression;
5880 if (!expression_returns(expr))
5883 next = stmt->base.next;
5887 case STATEMENT_CONTINUE: {
5888 statement_t *parent = stmt;
5890 parent = parent->base.parent;
5891 if (parent == NULL) /* continue not within loop */
5895 switch (parent->kind) {
5896 case STATEMENT_WHILE: goto continue_while;
5897 case STATEMENT_DO_WHILE: goto continue_do_while;
5898 case STATEMENT_FOR: goto continue_for;
5905 case STATEMENT_BREAK: {
5906 statement_t *parent = stmt;
5908 parent = parent->base.parent;
5909 if (parent == NULL) /* break not within loop/switch */
5912 switch (parent->kind) {
5913 case STATEMENT_SWITCH:
5914 case STATEMENT_WHILE:
5915 case STATEMENT_DO_WHILE:
5918 next = parent->base.next;
5919 goto found_break_parent;
5928 case STATEMENT_GOTO:
5929 if (stmt->gotos.expression) {
5930 if (!expression_returns(stmt->gotos.expression))
5933 statement_t *parent = stmt->base.parent;
5934 if (parent == NULL) /* top level goto */
5938 next = stmt->gotos.label->statement;
5939 if (next == NULL) /* missing label */
5944 case STATEMENT_LABEL:
5945 next = stmt->label.statement;
5948 case STATEMENT_CASE_LABEL:
5949 next = stmt->case_label.statement;
5952 case STATEMENT_WHILE: {
5953 while_statement_t const *const whiles = &stmt->whiles;
5954 expression_t const *const cond = whiles->condition;
5956 if (!expression_returns(cond))
5959 int const val = determine_truth(cond);
5962 check_reachable(whiles->body);
5967 next = stmt->base.next;
5971 case STATEMENT_DO_WHILE:
5972 next = stmt->do_while.body;
5975 case STATEMENT_FOR: {
5976 for_statement_t *const fors = &stmt->fors;
5978 if (fors->condition_reachable)
5980 fors->condition_reachable = true;
5982 expression_t const *const cond = fors->condition;
5987 } else if (expression_returns(cond)) {
5988 val = determine_truth(cond);
5994 check_reachable(fors->body);
5999 next = stmt->base.next;
6003 case STATEMENT_MS_TRY: {
6004 ms_try_statement_t const *const ms_try = &stmt->ms_try;
6005 check_reachable(ms_try->try_statement);
6006 next = ms_try->final_statement;
6010 case STATEMENT_LEAVE: {
6011 statement_t *parent = stmt;
6013 parent = parent->base.parent;
6014 if (parent == NULL) /* __leave not within __try */
6017 if (parent->kind == STATEMENT_MS_TRY) {
6019 next = parent->ms_try.final_statement;
6027 while (next == NULL) {
6028 next = last->base.parent;
6030 noreturn_candidate = false;
6032 type_t *const type = current_function->base.type;
6033 assert(is_type_function(type));
6034 type_t *const ret = skip_typeref(type->function.return_type);
6035 if (warning.return_type &&
6036 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
6037 is_type_valid(ret) &&
6038 !is_sym_main(current_function->base.base.symbol)) {
6039 warningf(&stmt->base.source_position,
6040 "control reaches end of non-void function");
6045 switch (next->kind) {
6046 case STATEMENT_INVALID:
6047 case STATEMENT_EMPTY:
6048 case STATEMENT_DECLARATION:
6049 case STATEMENT_LOCAL_LABEL:
6050 case STATEMENT_EXPRESSION:
6052 case STATEMENT_RETURN:
6053 case STATEMENT_CONTINUE:
6054 case STATEMENT_BREAK:
6055 case STATEMENT_GOTO:
6056 case STATEMENT_LEAVE:
6057 panic("invalid control flow in function");
6059 case STATEMENT_COMPOUND:
6061 case STATEMENT_SWITCH:
6062 case STATEMENT_LABEL:
6063 case STATEMENT_CASE_LABEL:
6065 next = next->base.next;
6068 case STATEMENT_WHILE: {
6070 if (next->base.reachable)
6072 next->base.reachable = true;
6074 while_statement_t const *const whiles = &next->whiles;
6075 expression_t const *const cond = whiles->condition;
6077 if (!expression_returns(cond))
6080 int const val = determine_truth(cond);
6083 check_reachable(whiles->body);
6089 next = next->base.next;
6093 case STATEMENT_DO_WHILE: {
6095 if (next->base.reachable)
6097 next->base.reachable = true;
6099 do_while_statement_t const *const dw = &next->do_while;
6100 expression_t const *const cond = dw->condition;
6102 if (!expression_returns(cond))
6105 int const val = determine_truth(cond);
6108 check_reachable(dw->body);
6114 next = next->base.next;
6118 case STATEMENT_FOR: {
6120 for_statement_t *const fors = &next->fors;
6122 fors->step_reachable = true;
6124 if (fors->condition_reachable)
6126 fors->condition_reachable = true;
6128 expression_t const *const cond = fors->condition;
6133 } else if (expression_returns(cond)) {
6134 val = determine_truth(cond);
6140 check_reachable(fors->body);
6146 next = next->base.next;
6150 case STATEMENT_MS_TRY:
6152 next = next->ms_try.final_statement;
6157 check_reachable(next);
6160 static void check_unreachable(statement_t* const stmt, void *const env)
6164 switch (stmt->kind) {
6165 case STATEMENT_DO_WHILE:
6166 if (!stmt->base.reachable) {
6167 expression_t const *const cond = stmt->do_while.condition;
6168 if (determine_truth(cond) >= 0) {
6169 warningf(&cond->base.source_position,
6170 "condition of do-while-loop is unreachable");
6175 case STATEMENT_FOR: {
6176 for_statement_t const* const fors = &stmt->fors;
6178 // if init and step are unreachable, cond is unreachable, too
6179 if (!stmt->base.reachable && !fors->step_reachable) {
6180 warningf(&stmt->base.source_position, "statement is unreachable");
6182 if (!stmt->base.reachable && fors->initialisation != NULL) {
6183 warningf(&fors->initialisation->base.source_position,
6184 "initialisation of for-statement is unreachable");
6187 if (!fors->condition_reachable && fors->condition != NULL) {
6188 warningf(&fors->condition->base.source_position,
6189 "condition of for-statement is unreachable");
6192 if (!fors->step_reachable && fors->step != NULL) {
6193 warningf(&fors->step->base.source_position,
6194 "step of for-statement is unreachable");
6200 case STATEMENT_COMPOUND:
6201 if (stmt->compound.statements != NULL)
6203 goto warn_unreachable;
6205 case STATEMENT_DECLARATION: {
6206 /* Only warn if there is at least one declarator with an initializer.
6207 * This typically occurs in switch statements. */
6208 declaration_statement_t const *const decl = &stmt->declaration;
6209 entity_t const * ent = decl->declarations_begin;
6210 entity_t const *const last = decl->declarations_end;
6211 for (;; ent = ent->base.next) {
6212 if (ent->kind == ENTITY_VARIABLE &&
6213 ent->variable.initializer != NULL) {
6214 goto warn_unreachable;
6223 if (!stmt->base.reachable)
6224 warningf(&stmt->base.source_position, "statement is unreachable");
6229 static void parse_external_declaration(void)
6231 /* function-definitions and declarations both start with declaration
6233 declaration_specifiers_t specifiers;
6234 memset(&specifiers, 0, sizeof(specifiers));
6236 add_anchor_token(';');
6237 parse_declaration_specifiers(&specifiers);
6238 rem_anchor_token(';');
6240 /* must be a declaration */
6241 if (token.type == ';') {
6242 parse_anonymous_declaration_rest(&specifiers);
6246 add_anchor_token(',');
6247 add_anchor_token('=');
6248 add_anchor_token(';');
6249 add_anchor_token('{');
6251 /* declarator is common to both function-definitions and declarations */
6252 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6254 rem_anchor_token('{');
6255 rem_anchor_token(';');
6256 rem_anchor_token('=');
6257 rem_anchor_token(',');
6259 /* must be a declaration */
6260 switch (token.type) {
6264 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
6269 /* must be a function definition */
6270 parse_kr_declaration_list(ndeclaration);
6272 if (token.type != '{') {
6273 parse_error_expected("while parsing function definition", '{', NULL);
6274 eat_until_matching_token(';');
6278 assert(is_declaration(ndeclaration));
6279 type_t *type = skip_typeref(ndeclaration->declaration.type);
6281 if (!is_type_function(type)) {
6282 if (is_type_valid(type)) {
6283 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6284 type, ndeclaration->base.symbol);
6290 if (warning.aggregate_return &&
6291 is_type_compound(skip_typeref(type->function.return_type))) {
6292 warningf(HERE, "function '%Y' returns an aggregate",
6293 ndeclaration->base.symbol);
6295 if (warning.traditional && !type->function.unspecified_parameters) {
6296 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6297 ndeclaration->base.symbol);
6299 if (warning.old_style_definition && type->function.unspecified_parameters) {
6300 warningf(HERE, "old-style function definition '%Y'",
6301 ndeclaration->base.symbol);
6304 /* § 6.7.5.3 (14) a function definition with () means no
6305 * parameters (and not unspecified parameters) */
6306 if (type->function.unspecified_parameters
6307 && type->function.parameters == NULL
6308 && !type->function.kr_style_parameters) {
6309 type_t *duplicate = duplicate_type(type);
6310 duplicate->function.unspecified_parameters = false;
6312 type = typehash_insert(duplicate);
6313 if (type != duplicate) {
6314 obstack_free(type_obst, duplicate);
6316 ndeclaration->declaration.type = type;
6319 entity_t *const entity = record_entity(ndeclaration, true);
6320 assert(entity->kind == ENTITY_FUNCTION);
6321 assert(ndeclaration->kind == ENTITY_FUNCTION);
6323 function_t *function = &entity->function;
6324 if (ndeclaration != entity) {
6325 function->parameters = ndeclaration->function.parameters;
6327 assert(is_declaration(entity));
6328 type = skip_typeref(entity->declaration.type);
6330 /* push function parameters and switch scope */
6331 size_t const top = environment_top();
6332 scope_t *old_scope = scope_push(&function->parameters);
6334 entity_t *parameter = function->parameters.entities;
6335 for (; parameter != NULL; parameter = parameter->base.next) {
6336 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6337 parameter->base.parent_scope = current_scope;
6339 assert(parameter->base.parent_scope == NULL
6340 || parameter->base.parent_scope == current_scope);
6341 parameter->base.parent_scope = current_scope;
6342 if (parameter->base.symbol == NULL) {
6343 errorf(¶meter->base.source_position, "parameter name omitted");
6346 environment_push(parameter);
6349 if (function->statement != NULL) {
6350 parser_error_multiple_definition(entity, HERE);
6353 /* parse function body */
6354 int label_stack_top = label_top();
6355 function_t *old_current_function = current_function;
6356 current_function = function;
6357 current_parent = NULL;
6360 goto_anchor = &goto_first;
6362 label_anchor = &label_first;
6364 statement_t *const body = parse_compound_statement(false);
6365 function->statement = body;
6368 check_declarations();
6369 if (warning.return_type ||
6370 warning.unreachable_code ||
6371 (warning.missing_noreturn
6372 && !(function->base.modifiers & DM_NORETURN))) {
6373 noreturn_candidate = true;
6374 check_reachable(body);
6375 if (warning.unreachable_code)
6376 walk_statements(body, check_unreachable, NULL);
6377 if (warning.missing_noreturn &&
6378 noreturn_candidate &&
6379 !(function->base.modifiers & DM_NORETURN)) {
6380 warningf(&body->base.source_position,
6381 "function '%#T' is candidate for attribute 'noreturn'",
6382 type, entity->base.symbol);
6386 assert(current_parent == NULL);
6387 assert(current_function == function);
6388 current_function = old_current_function;
6389 label_pop_to(label_stack_top);
6392 assert(current_scope == &function->parameters);
6393 scope_pop(old_scope);
6394 environment_pop_to(top);
6397 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6398 source_position_t *source_position,
6399 const symbol_t *symbol)
6401 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6403 type->bitfield.base_type = base_type;
6404 type->bitfield.size_expression = size;
6407 type_t *skipped_type = skip_typeref(base_type);
6408 if (!is_type_integer(skipped_type)) {
6409 errorf(HERE, "bitfield base type '%T' is not an integer type",
6413 bit_size = skipped_type->base.size * 8;
6416 if (is_constant_expression(size)) {
6417 long v = fold_constant(size);
6420 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6421 } else if (v == 0) {
6422 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6423 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6424 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6426 type->bitfield.bit_size = v;
6433 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6435 entity_t *iter = compound->members.entities;
6436 for (; iter != NULL; iter = iter->base.next) {
6437 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6440 if (iter->base.symbol == symbol) {
6442 } else if (iter->base.symbol == NULL) {
6443 type_t *type = skip_typeref(iter->declaration.type);
6444 if (is_type_compound(type)) {
6446 = find_compound_entry(type->compound.compound, symbol);
6457 static void parse_compound_declarators(compound_t *compound,
6458 const declaration_specifiers_t *specifiers)
6463 if (token.type == ':') {
6464 source_position_t source_position = *HERE;
6467 type_t *base_type = specifiers->type;
6468 expression_t *size = parse_constant_expression();
6470 type_t *type = make_bitfield_type(base_type, size,
6471 &source_position, sym_anonymous);
6473 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6474 entity->base.namespc = NAMESPACE_NORMAL;
6475 entity->base.source_position = source_position;
6476 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6477 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6478 entity->declaration.modifiers = specifiers->modifiers;
6479 entity->declaration.type = type;
6481 entity = parse_declarator(specifiers,
6482 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6483 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6485 if (token.type == ':') {
6486 source_position_t source_position = *HERE;
6488 expression_t *size = parse_constant_expression();
6490 type_t *type = entity->declaration.type;
6491 type_t *bitfield_type = make_bitfield_type(type, size,
6492 &source_position, entity->base.symbol);
6493 entity->declaration.type = bitfield_type;
6497 /* make sure we don't define a symbol multiple times */
6498 symbol_t *symbol = entity->base.symbol;
6499 if (symbol != NULL) {
6500 entity_t *prev = find_compound_entry(compound, symbol);
6503 errorf(&entity->base.source_position,
6504 "multiple declarations of symbol '%Y' (declared %P)",
6505 symbol, &prev->base.source_position);
6509 append_entity(&compound->members, entity);
6511 type_t *orig_type = entity->declaration.type;
6512 type_t *type = skip_typeref(orig_type);
6513 if (is_type_function(type)) {
6514 errorf(&entity->base.source_position,
6515 "compound member '%Y' must not have function type '%T'",
6516 entity->base.symbol, orig_type);
6517 } else if (is_type_incomplete(type)) {
6518 /* §6.7.2.1:16 flexible array member */
6519 if (is_type_array(type) &&
6520 token.type == ';' &&
6521 look_ahead(1)->type == '}') {
6522 compound->has_flexible_member = true;
6524 errorf(&entity->base.source_position,
6525 "compound member '%Y' has incomplete type '%T'",
6526 entity->base.symbol, orig_type);
6530 if (token.type != ',')
6537 anonymous_entity = NULL;
6540 static void parse_compound_type_entries(compound_t *compound)
6543 add_anchor_token('}');
6545 while (token.type != '}') {
6546 if (token.type == T_EOF) {
6547 errorf(HERE, "EOF while parsing struct");
6550 declaration_specifiers_t specifiers;
6551 memset(&specifiers, 0, sizeof(specifiers));
6552 parse_declaration_specifiers(&specifiers);
6554 parse_compound_declarators(compound, &specifiers);
6556 rem_anchor_token('}');
6560 compound->complete = true;
6563 static type_t *parse_typename(void)
6565 declaration_specifiers_t specifiers;
6566 memset(&specifiers, 0, sizeof(specifiers));
6567 parse_declaration_specifiers(&specifiers);
6568 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6569 specifiers.thread_local) {
6570 /* TODO: improve error message, user does probably not know what a
6571 * storage class is...
6573 errorf(HERE, "typename may not have a storage class");
6576 type_t *result = parse_abstract_declarator(specifiers.type);
6584 typedef expression_t* (*parse_expression_function)(void);
6585 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6587 typedef struct expression_parser_function_t expression_parser_function_t;
6588 struct expression_parser_function_t {
6589 parse_expression_function parser;
6590 unsigned infix_precedence;
6591 parse_expression_infix_function infix_parser;
6594 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6597 * Prints an error message if an expression was expected but not read
6599 static expression_t *expected_expression_error(void)
6601 /* skip the error message if the error token was read */
6602 if (token.type != T_ERROR) {
6603 errorf(HERE, "expected expression, got token %K", &token);
6607 return create_invalid_expression();
6611 * Parse a string constant.
6613 static expression_t *parse_string_const(void)
6616 if (token.type == T_STRING_LITERAL) {
6617 string_t res = token.v.string;
6619 while (token.type == T_STRING_LITERAL) {
6620 res = concat_strings(&res, &token.v.string);
6623 if (token.type != T_WIDE_STRING_LITERAL) {
6624 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6625 /* note: that we use type_char_ptr here, which is already the
6626 * automatic converted type. revert_automatic_type_conversion
6627 * will construct the array type */
6628 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6629 cnst->string.value = res;
6633 wres = concat_string_wide_string(&res, &token.v.wide_string);
6635 wres = token.v.wide_string;
6640 switch (token.type) {
6641 case T_WIDE_STRING_LITERAL:
6642 wres = concat_wide_strings(&wres, &token.v.wide_string);
6645 case T_STRING_LITERAL:
6646 wres = concat_wide_string_string(&wres, &token.v.string);
6650 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6651 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6652 cnst->wide_string.value = wres;
6661 * Parse a boolean constant.
6663 static expression_t *parse_bool_const(bool value)
6665 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6666 cnst->base.type = type_bool;
6667 cnst->conste.v.int_value = value;
6675 * Parse an integer constant.
6677 static expression_t *parse_int_const(void)
6679 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6680 cnst->base.type = token.datatype;
6681 cnst->conste.v.int_value = token.v.intvalue;
6689 * Parse a character constant.
6691 static expression_t *parse_character_constant(void)
6693 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6694 cnst->base.type = token.datatype;
6695 cnst->conste.v.character = token.v.string;
6697 if (cnst->conste.v.character.size != 1) {
6699 errorf(HERE, "more than 1 character in character constant");
6700 } else if (warning.multichar) {
6701 warningf(HERE, "multi-character character constant");
6710 * Parse a wide character constant.
6712 static expression_t *parse_wide_character_constant(void)
6714 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6715 cnst->base.type = token.datatype;
6716 cnst->conste.v.wide_character = token.v.wide_string;
6718 if (cnst->conste.v.wide_character.size != 1) {
6720 errorf(HERE, "more than 1 character in character constant");
6721 } else if (warning.multichar) {
6722 warningf(HERE, "multi-character character constant");
6731 * Parse a float constant.
6733 static expression_t *parse_float_const(void)
6735 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6736 cnst->base.type = token.datatype;
6737 cnst->conste.v.float_value = token.v.floatvalue;
6744 static entity_t *create_implicit_function(symbol_t *symbol,
6745 const source_position_t *source_position)
6747 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6748 ntype->function.return_type = type_int;
6749 ntype->function.unspecified_parameters = true;
6751 type_t *type = typehash_insert(ntype);
6752 if (type != ntype) {
6756 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6757 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6758 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6759 entity->declaration.type = type;
6760 entity->declaration.implicit = true;
6761 entity->base.symbol = symbol;
6762 entity->base.source_position = *source_position;
6764 bool strict_prototypes_old = warning.strict_prototypes;
6765 warning.strict_prototypes = false;
6766 record_entity(entity, false);
6767 warning.strict_prototypes = strict_prototypes_old;
6773 * Creates a return_type (func)(argument_type) function type if not
6776 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6777 type_t *argument_type2)
6779 function_parameter_t *parameter2
6780 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6781 memset(parameter2, 0, sizeof(parameter2[0]));
6782 parameter2->type = argument_type2;
6784 function_parameter_t *parameter1
6785 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6786 memset(parameter1, 0, sizeof(parameter1[0]));
6787 parameter1->type = argument_type1;
6788 parameter1->next = parameter2;
6790 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6791 type->function.return_type = return_type;
6792 type->function.parameters = parameter1;
6794 type_t *result = typehash_insert(type);
6795 if (result != type) {
6803 * Creates a return_type (func)(argument_type) function type if not
6806 * @param return_type the return type
6807 * @param argument_type the argument type
6809 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6811 function_parameter_t *parameter
6812 = obstack_alloc(type_obst, sizeof(parameter[0]));
6813 memset(parameter, 0, sizeof(parameter[0]));
6814 parameter->type = argument_type;
6816 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6817 type->function.return_type = return_type;
6818 type->function.parameters = parameter;
6820 type_t *result = typehash_insert(type);
6821 if (result != type) {
6828 static type_t *make_function_0_type(type_t *return_type)
6830 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6831 type->function.return_type = return_type;
6832 type->function.parameters = NULL;
6834 type_t *result = typehash_insert(type);
6835 if (result != type) {
6843 * Creates a function type for some function like builtins.
6845 * @param symbol the symbol describing the builtin
6847 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6849 switch (symbol->ID) {
6850 case T___builtin_alloca:
6851 return make_function_1_type(type_void_ptr, type_size_t);
6852 case T___builtin_huge_val:
6853 return make_function_0_type(type_double);
6854 case T___builtin_inf:
6855 return make_function_0_type(type_double);
6856 case T___builtin_inff:
6857 return make_function_0_type(type_float);
6858 case T___builtin_infl:
6859 return make_function_0_type(type_long_double);
6860 case T___builtin_nan:
6861 return make_function_1_type(type_double, type_char_ptr);
6862 case T___builtin_nanf:
6863 return make_function_1_type(type_float, type_char_ptr);
6864 case T___builtin_nanl:
6865 return make_function_1_type(type_long_double, type_char_ptr);
6866 case T___builtin_va_end:
6867 return make_function_1_type(type_void, type_valist);
6868 case T___builtin_expect:
6869 return make_function_2_type(type_long, type_long, type_long);
6871 internal_errorf(HERE, "not implemented builtin identifier found");
6876 * Performs automatic type cast as described in § 6.3.2.1.
6878 * @param orig_type the original type
6880 static type_t *automatic_type_conversion(type_t *orig_type)
6882 type_t *type = skip_typeref(orig_type);
6883 if (is_type_array(type)) {
6884 array_type_t *array_type = &type->array;
6885 type_t *element_type = array_type->element_type;
6886 unsigned qualifiers = array_type->base.qualifiers;
6888 return make_pointer_type(element_type, qualifiers);
6891 if (is_type_function(type)) {
6892 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6899 * reverts the automatic casts of array to pointer types and function
6900 * to function-pointer types as defined § 6.3.2.1
6902 type_t *revert_automatic_type_conversion(const expression_t *expression)
6904 switch (expression->kind) {
6905 case EXPR_REFERENCE: {
6906 entity_t *entity = expression->reference.entity;
6907 if (is_declaration(entity)) {
6908 return entity->declaration.type;
6909 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6910 return entity->enum_value.enum_type;
6912 panic("no declaration or enum in reference");
6917 entity_t *entity = expression->select.compound_entry;
6918 assert(is_declaration(entity));
6919 type_t *type = entity->declaration.type;
6920 return get_qualified_type(type,
6921 expression->base.type->base.qualifiers);
6924 case EXPR_UNARY_DEREFERENCE: {
6925 const expression_t *const value = expression->unary.value;
6926 type_t *const type = skip_typeref(value->base.type);
6927 assert(is_type_pointer(type));
6928 return type->pointer.points_to;
6931 case EXPR_BUILTIN_SYMBOL:
6932 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6934 case EXPR_ARRAY_ACCESS: {
6935 const expression_t *array_ref = expression->array_access.array_ref;
6936 type_t *type_left = skip_typeref(array_ref->base.type);
6937 if (!is_type_valid(type_left))
6939 assert(is_type_pointer(type_left));
6940 return type_left->pointer.points_to;
6943 case EXPR_STRING_LITERAL: {
6944 size_t size = expression->string.value.size;
6945 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6948 case EXPR_WIDE_STRING_LITERAL: {
6949 size_t size = expression->wide_string.value.size;
6950 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6953 case EXPR_COMPOUND_LITERAL:
6954 return expression->compound_literal.type;
6959 return expression->base.type;
6962 static expression_t *parse_reference(void)
6964 symbol_t *const symbol = token.v.symbol;
6966 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6968 if (entity == NULL) {
6969 if (!strict_mode && look_ahead(1)->type == '(') {
6970 /* an implicitly declared function */
6971 if (warning.error_implicit_function_declaration) {
6972 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6973 } else if (warning.implicit_function_declaration) {
6974 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6977 entity = create_implicit_function(symbol, HERE);
6979 errorf(HERE, "unknown identifier '%Y' found.", symbol);
6980 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6986 if (is_declaration(entity)) {
6987 orig_type = entity->declaration.type;
6988 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6989 orig_type = entity->enum_value.enum_type;
6990 } else if (entity->kind == ENTITY_TYPEDEF) {
6991 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6994 return create_invalid_expression();
6996 panic("expected declaration or enum value in reference");
6999 /* we always do the auto-type conversions; the & and sizeof parser contains
7000 * code to revert this! */
7001 type_t *type = automatic_type_conversion(orig_type);
7003 expression_kind_t kind = EXPR_REFERENCE;
7004 if (entity->kind == ENTITY_ENUM_VALUE)
7005 kind = EXPR_REFERENCE_ENUM_VALUE;
7007 expression_t *expression = allocate_expression_zero(kind);
7008 expression->reference.entity = entity;
7009 expression->base.type = type;
7011 /* this declaration is used */
7012 if (is_declaration(entity)) {
7013 entity->declaration.used = true;
7016 if (entity->base.parent_scope != file_scope
7017 && entity->base.parent_scope->depth < current_function->parameters.depth
7018 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
7019 if (entity->kind == ENTITY_VARIABLE) {
7020 /* access of a variable from an outer function */
7021 entity->variable.address_taken = true;
7022 } else if (entity->kind == ENTITY_PARAMETER) {
7023 entity->parameter.address_taken = true;
7025 current_function->need_closure = true;
7028 /* check for deprecated functions */
7029 if (warning.deprecated_declarations
7030 && is_declaration(entity)
7031 && entity->declaration.modifiers & DM_DEPRECATED) {
7032 declaration_t *declaration = &entity->declaration;
7034 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
7035 "function" : "variable";
7037 if (declaration->deprecated_string != NULL) {
7038 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
7039 prefix, entity->base.symbol, &entity->base.source_position,
7040 declaration->deprecated_string);
7042 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
7043 entity->base.symbol, &entity->base.source_position);
7047 if (warning.init_self && entity == current_init_decl && !in_type_prop
7048 && entity->kind == ENTITY_VARIABLE) {
7049 current_init_decl = NULL;
7050 warningf(HERE, "variable '%#T' is initialized by itself",
7051 entity->declaration.type, entity->base.symbol);
7058 static bool semantic_cast(expression_t *cast)
7060 expression_t *expression = cast->unary.value;
7061 type_t *orig_dest_type = cast->base.type;
7062 type_t *orig_type_right = expression->base.type;
7063 type_t const *dst_type = skip_typeref(orig_dest_type);
7064 type_t const *src_type = skip_typeref(orig_type_right);
7065 source_position_t const *pos = &cast->base.source_position;
7067 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
7068 if (dst_type == type_void)
7071 /* only integer and pointer can be casted to pointer */
7072 if (is_type_pointer(dst_type) &&
7073 !is_type_pointer(src_type) &&
7074 !is_type_integer(src_type) &&
7075 is_type_valid(src_type)) {
7076 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
7080 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
7081 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
7085 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
7086 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
7090 if (warning.cast_qual &&
7091 is_type_pointer(src_type) &&
7092 is_type_pointer(dst_type)) {
7093 type_t *src = skip_typeref(src_type->pointer.points_to);
7094 type_t *dst = skip_typeref(dst_type->pointer.points_to);
7095 unsigned missing_qualifiers =
7096 src->base.qualifiers & ~dst->base.qualifiers;
7097 if (missing_qualifiers != 0) {
7099 "cast discards qualifiers '%Q' in pointer target type of '%T'",
7100 missing_qualifiers, orig_type_right);
7106 static expression_t *parse_compound_literal(type_t *type)
7108 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
7110 parse_initializer_env_t env;
7113 env.must_be_constant = false;
7114 initializer_t *initializer = parse_initializer(&env);
7117 expression->compound_literal.initializer = initializer;
7118 expression->compound_literal.type = type;
7119 expression->base.type = automatic_type_conversion(type);
7125 * Parse a cast expression.
7127 static expression_t *parse_cast(void)
7129 add_anchor_token(')');
7131 source_position_t source_position = token.source_position;
7133 type_t *type = parse_typename();
7135 rem_anchor_token(')');
7138 if (token.type == '{') {
7139 return parse_compound_literal(type);
7142 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
7143 cast->base.source_position = source_position;
7145 expression_t *value = parse_sub_expression(PREC_CAST);
7146 cast->base.type = type;
7147 cast->unary.value = value;
7149 if (! semantic_cast(cast)) {
7150 /* TODO: record the error in the AST. else it is impossible to detect it */
7155 return create_invalid_expression();
7159 * Parse a statement expression.
7161 static expression_t *parse_statement_expression(void)
7163 add_anchor_token(')');
7165 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
7167 statement_t *statement = parse_compound_statement(true);
7168 expression->statement.statement = statement;
7170 /* find last statement and use its type */
7171 type_t *type = type_void;
7172 const statement_t *stmt = statement->compound.statements;
7174 while (stmt->base.next != NULL)
7175 stmt = stmt->base.next;
7177 if (stmt->kind == STATEMENT_EXPRESSION) {
7178 type = stmt->expression.expression->base.type;
7180 } else if (warning.other) {
7181 warningf(&expression->base.source_position, "empty statement expression ({})");
7183 expression->base.type = type;
7185 rem_anchor_token(')');
7193 * Parse a parenthesized expression.
7195 static expression_t *parse_parenthesized_expression(void)
7199 switch (token.type) {
7201 /* gcc extension: a statement expression */
7202 return parse_statement_expression();
7206 return parse_cast();
7208 if (is_typedef_symbol(token.v.symbol)) {
7209 return parse_cast();
7213 add_anchor_token(')');
7214 expression_t *result = parse_expression();
7215 rem_anchor_token(')');
7222 static expression_t *parse_function_keyword(void)
7226 if (current_function == NULL) {
7227 errorf(HERE, "'__func__' used outside of a function");
7230 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7231 expression->base.type = type_char_ptr;
7232 expression->funcname.kind = FUNCNAME_FUNCTION;
7239 static expression_t *parse_pretty_function_keyword(void)
7241 if (current_function == NULL) {
7242 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7245 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7246 expression->base.type = type_char_ptr;
7247 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7249 eat(T___PRETTY_FUNCTION__);
7254 static expression_t *parse_funcsig_keyword(void)
7256 if (current_function == NULL) {
7257 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7260 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7261 expression->base.type = type_char_ptr;
7262 expression->funcname.kind = FUNCNAME_FUNCSIG;
7269 static expression_t *parse_funcdname_keyword(void)
7271 if (current_function == NULL) {
7272 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7275 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7276 expression->base.type = type_char_ptr;
7277 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7279 eat(T___FUNCDNAME__);
7284 static designator_t *parse_designator(void)
7286 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7287 result->source_position = *HERE;
7289 if (token.type != T_IDENTIFIER) {
7290 parse_error_expected("while parsing member designator",
7291 T_IDENTIFIER, NULL);
7294 result->symbol = token.v.symbol;
7297 designator_t *last_designator = result;
7299 if (token.type == '.') {
7301 if (token.type != T_IDENTIFIER) {
7302 parse_error_expected("while parsing member designator",
7303 T_IDENTIFIER, NULL);
7306 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7307 designator->source_position = *HERE;
7308 designator->symbol = token.v.symbol;
7311 last_designator->next = designator;
7312 last_designator = designator;
7315 if (token.type == '[') {
7317 add_anchor_token(']');
7318 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7319 designator->source_position = *HERE;
7320 designator->array_index = parse_expression();
7321 rem_anchor_token(']');
7323 if (designator->array_index == NULL) {
7327 last_designator->next = designator;
7328 last_designator = designator;
7340 * Parse the __builtin_offsetof() expression.
7342 static expression_t *parse_offsetof(void)
7344 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7345 expression->base.type = type_size_t;
7347 eat(T___builtin_offsetof);
7350 add_anchor_token(',');
7351 type_t *type = parse_typename();
7352 rem_anchor_token(',');
7354 add_anchor_token(')');
7355 designator_t *designator = parse_designator();
7356 rem_anchor_token(')');
7359 expression->offsetofe.type = type;
7360 expression->offsetofe.designator = designator;
7363 memset(&path, 0, sizeof(path));
7364 path.top_type = type;
7365 path.path = NEW_ARR_F(type_path_entry_t, 0);
7367 descend_into_subtype(&path);
7369 if (!walk_designator(&path, designator, true)) {
7370 return create_invalid_expression();
7373 DEL_ARR_F(path.path);
7377 return create_invalid_expression();
7381 * Parses a _builtin_va_start() expression.
7383 static expression_t *parse_va_start(void)
7385 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7387 eat(T___builtin_va_start);
7390 add_anchor_token(',');
7391 expression->va_starte.ap = parse_assignment_expression();
7392 rem_anchor_token(',');
7394 expression_t *const expr = parse_assignment_expression();
7395 if (expr->kind == EXPR_REFERENCE) {
7396 entity_t *const entity = expr->reference.entity;
7397 if (entity->base.parent_scope != ¤t_function->parameters
7398 || entity->base.next != NULL
7399 || entity->kind != ENTITY_PARAMETER) {
7400 errorf(&expr->base.source_position,
7401 "second argument of 'va_start' must be last parameter of the current function");
7403 expression->va_starte.parameter = &entity->variable;
7410 return create_invalid_expression();
7414 * Parses a _builtin_va_arg() expression.
7416 static expression_t *parse_va_arg(void)
7418 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7420 eat(T___builtin_va_arg);
7423 expression->va_arge.ap = parse_assignment_expression();
7425 expression->base.type = parse_typename();
7430 return create_invalid_expression();
7433 static expression_t *parse_builtin_symbol(void)
7435 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7437 symbol_t *symbol = token.v.symbol;
7439 expression->builtin_symbol.symbol = symbol;
7442 type_t *type = get_builtin_symbol_type(symbol);
7443 type = automatic_type_conversion(type);
7445 expression->base.type = type;
7450 * Parses a __builtin_constant() expression.
7452 static expression_t *parse_builtin_constant(void)
7454 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7456 eat(T___builtin_constant_p);
7459 add_anchor_token(')');
7460 expression->builtin_constant.value = parse_assignment_expression();
7461 rem_anchor_token(')');
7463 expression->base.type = type_int;
7467 return create_invalid_expression();
7471 * Parses a __builtin_prefetch() expression.
7473 static expression_t *parse_builtin_prefetch(void)
7475 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7477 eat(T___builtin_prefetch);
7480 add_anchor_token(')');
7481 expression->builtin_prefetch.adr = parse_assignment_expression();
7482 if (token.type == ',') {
7484 expression->builtin_prefetch.rw = parse_assignment_expression();
7486 if (token.type == ',') {
7488 expression->builtin_prefetch.locality = parse_assignment_expression();
7490 rem_anchor_token(')');
7492 expression->base.type = type_void;
7496 return create_invalid_expression();
7500 * Parses a __builtin_is_*() compare expression.
7502 static expression_t *parse_compare_builtin(void)
7504 expression_t *expression;
7506 switch (token.type) {
7507 case T___builtin_isgreater:
7508 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7510 case T___builtin_isgreaterequal:
7511 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7513 case T___builtin_isless:
7514 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7516 case T___builtin_islessequal:
7517 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7519 case T___builtin_islessgreater:
7520 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7522 case T___builtin_isunordered:
7523 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7526 internal_errorf(HERE, "invalid compare builtin found");
7528 expression->base.source_position = *HERE;
7532 expression->binary.left = parse_assignment_expression();
7534 expression->binary.right = parse_assignment_expression();
7537 type_t *const orig_type_left = expression->binary.left->base.type;
7538 type_t *const orig_type_right = expression->binary.right->base.type;
7540 type_t *const type_left = skip_typeref(orig_type_left);
7541 type_t *const type_right = skip_typeref(orig_type_right);
7542 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7543 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7544 type_error_incompatible("invalid operands in comparison",
7545 &expression->base.source_position, orig_type_left, orig_type_right);
7548 semantic_comparison(&expression->binary);
7553 return create_invalid_expression();
7558 * Parses a __builtin_expect() expression.
7560 static expression_t *parse_builtin_expect(void)
7562 expression_t *expression
7563 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7565 eat(T___builtin_expect);
7568 expression->binary.left = parse_assignment_expression();
7570 expression->binary.right = parse_constant_expression();
7573 expression->base.type = expression->binary.left->base.type;
7577 return create_invalid_expression();
7582 * Parses a MS assume() expression.
7584 static expression_t *parse_assume(void)
7586 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7591 add_anchor_token(')');
7592 expression->unary.value = parse_assignment_expression();
7593 rem_anchor_token(')');
7596 expression->base.type = type_void;
7599 return create_invalid_expression();
7603 * Return the declaration for a given label symbol or create a new one.
7605 * @param symbol the symbol of the label
7607 static label_t *get_label(symbol_t *symbol)
7610 assert(current_function != NULL);
7612 label = get_entity(symbol, NAMESPACE_LABEL);
7613 /* if we found a local label, we already created the declaration */
7614 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7615 if (label->base.parent_scope != current_scope) {
7616 assert(label->base.parent_scope->depth < current_scope->depth);
7617 current_function->goto_to_outer = true;
7619 return &label->label;
7622 label = get_entity(symbol, NAMESPACE_LABEL);
7623 /* if we found a label in the same function, then we already created the
7626 && label->base.parent_scope == ¤t_function->parameters) {
7627 return &label->label;
7630 /* otherwise we need to create a new one */
7631 label = allocate_entity_zero(ENTITY_LABEL);
7632 label->base.namespc = NAMESPACE_LABEL;
7633 label->base.symbol = symbol;
7637 return &label->label;
7641 * Parses a GNU && label address expression.
7643 static expression_t *parse_label_address(void)
7645 source_position_t source_position = token.source_position;
7647 if (token.type != T_IDENTIFIER) {
7648 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7651 symbol_t *symbol = token.v.symbol;
7654 label_t *label = get_label(symbol);
7656 label->address_taken = true;
7658 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7659 expression->base.source_position = source_position;
7661 /* label address is threaten as a void pointer */
7662 expression->base.type = type_void_ptr;
7663 expression->label_address.label = label;
7666 return create_invalid_expression();
7670 * Parse a microsoft __noop expression.
7672 static expression_t *parse_noop_expression(void)
7674 /* the result is a (int)0 */
7675 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7676 cnst->base.type = type_int;
7677 cnst->conste.v.int_value = 0;
7678 cnst->conste.is_ms_noop = true;
7682 if (token.type == '(') {
7683 /* parse arguments */
7685 add_anchor_token(')');
7686 add_anchor_token(',');
7688 if (token.type != ')') {
7690 (void)parse_assignment_expression();
7691 if (token.type != ',')
7697 rem_anchor_token(',');
7698 rem_anchor_token(')');
7706 * Parses a primary expression.
7708 static expression_t *parse_primary_expression(void)
7710 switch (token.type) {
7711 case T_false: return parse_bool_const(false);
7712 case T_true: return parse_bool_const(true);
7713 case T_INTEGER: return parse_int_const();
7714 case T_CHARACTER_CONSTANT: return parse_character_constant();
7715 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7716 case T_FLOATINGPOINT: return parse_float_const();
7717 case T_STRING_LITERAL:
7718 case T_WIDE_STRING_LITERAL: return parse_string_const();
7719 case T_IDENTIFIER: return parse_reference();
7720 case T___FUNCTION__:
7721 case T___func__: return parse_function_keyword();
7722 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7723 case T___FUNCSIG__: return parse_funcsig_keyword();
7724 case T___FUNCDNAME__: return parse_funcdname_keyword();
7725 case T___builtin_offsetof: return parse_offsetof();
7726 case T___builtin_va_start: return parse_va_start();
7727 case T___builtin_va_arg: return parse_va_arg();
7728 case T___builtin_expect:
7729 case T___builtin_alloca:
7730 case T___builtin_inf:
7731 case T___builtin_inff:
7732 case T___builtin_infl:
7733 case T___builtin_nan:
7734 case T___builtin_nanf:
7735 case T___builtin_nanl:
7736 case T___builtin_huge_val:
7737 case T___builtin_va_end: return parse_builtin_symbol();
7738 case T___builtin_isgreater:
7739 case T___builtin_isgreaterequal:
7740 case T___builtin_isless:
7741 case T___builtin_islessequal:
7742 case T___builtin_islessgreater:
7743 case T___builtin_isunordered: return parse_compare_builtin();
7744 case T___builtin_constant_p: return parse_builtin_constant();
7745 case T___builtin_prefetch: return parse_builtin_prefetch();
7746 case T__assume: return parse_assume();
7749 return parse_label_address();
7752 case '(': return parse_parenthesized_expression();
7753 case T___noop: return parse_noop_expression();
7756 errorf(HERE, "unexpected token %K, expected an expression", &token);
7757 return create_invalid_expression();
7761 * Check if the expression has the character type and issue a warning then.
7763 static void check_for_char_index_type(const expression_t *expression)
7765 type_t *const type = expression->base.type;
7766 const type_t *const base_type = skip_typeref(type);
7768 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7769 warning.char_subscripts) {
7770 warningf(&expression->base.source_position,
7771 "array subscript has type '%T'", type);
7775 static expression_t *parse_array_expression(expression_t *left)
7777 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7780 add_anchor_token(']');
7782 expression_t *inside = parse_expression();
7784 type_t *const orig_type_left = left->base.type;
7785 type_t *const orig_type_inside = inside->base.type;
7787 type_t *const type_left = skip_typeref(orig_type_left);
7788 type_t *const type_inside = skip_typeref(orig_type_inside);
7790 type_t *return_type;
7791 array_access_expression_t *array_access = &expression->array_access;
7792 if (is_type_pointer(type_left)) {
7793 return_type = type_left->pointer.points_to;
7794 array_access->array_ref = left;
7795 array_access->index = inside;
7796 check_for_char_index_type(inside);
7797 } else if (is_type_pointer(type_inside)) {
7798 return_type = type_inside->pointer.points_to;
7799 array_access->array_ref = inside;
7800 array_access->index = left;
7801 array_access->flipped = true;
7802 check_for_char_index_type(left);
7804 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7806 "array access on object with non-pointer types '%T', '%T'",
7807 orig_type_left, orig_type_inside);
7809 return_type = type_error_type;
7810 array_access->array_ref = left;
7811 array_access->index = inside;
7814 expression->base.type = automatic_type_conversion(return_type);
7816 rem_anchor_token(']');
7822 static expression_t *parse_typeprop(expression_kind_t const kind)
7824 expression_t *tp_expression = allocate_expression_zero(kind);
7825 tp_expression->base.type = type_size_t;
7827 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7829 /* we only refer to a type property, mark this case */
7830 bool old = in_type_prop;
7831 in_type_prop = true;
7834 expression_t *expression;
7835 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7837 add_anchor_token(')');
7838 orig_type = parse_typename();
7839 rem_anchor_token(')');
7842 if (token.type == '{') {
7843 /* It was not sizeof(type) after all. It is sizeof of an expression
7844 * starting with a compound literal */
7845 expression = parse_compound_literal(orig_type);
7846 goto typeprop_expression;
7849 expression = parse_sub_expression(PREC_UNARY);
7851 typeprop_expression:
7852 tp_expression->typeprop.tp_expression = expression;
7854 orig_type = revert_automatic_type_conversion(expression);
7855 expression->base.type = orig_type;
7858 tp_expression->typeprop.type = orig_type;
7859 type_t const* const type = skip_typeref(orig_type);
7860 char const* const wrong_type =
7861 is_type_incomplete(type) ? "incomplete" :
7862 type->kind == TYPE_FUNCTION ? "function designator" :
7863 type->kind == TYPE_BITFIELD ? "bitfield" :
7865 if (wrong_type != NULL) {
7866 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7867 errorf(&tp_expression->base.source_position,
7868 "operand of %s expression must not be of %s type '%T'",
7869 what, wrong_type, orig_type);
7874 return tp_expression;
7877 static expression_t *parse_sizeof(void)
7879 return parse_typeprop(EXPR_SIZEOF);
7882 static expression_t *parse_alignof(void)
7884 return parse_typeprop(EXPR_ALIGNOF);
7887 static expression_t *parse_select_expression(expression_t *compound)
7889 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7890 select->select.compound = compound;
7892 assert(token.type == '.' || token.type == T_MINUSGREATER);
7893 bool is_pointer = (token.type == T_MINUSGREATER);
7896 if (token.type != T_IDENTIFIER) {
7897 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7900 symbol_t *symbol = token.v.symbol;
7903 type_t *const orig_type = compound->base.type;
7904 type_t *const type = skip_typeref(orig_type);
7907 bool saw_error = false;
7908 if (is_type_pointer(type)) {
7911 "request for member '%Y' in something not a struct or union, but '%T'",
7915 type_left = skip_typeref(type->pointer.points_to);
7917 if (is_pointer && is_type_valid(type)) {
7918 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7925 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7926 type_left->kind == TYPE_COMPOUND_UNION) {
7927 compound_t *compound = type_left->compound.compound;
7929 if (!compound->complete) {
7930 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7932 goto create_error_entry;
7935 entry = find_compound_entry(compound, symbol);
7936 if (entry == NULL) {
7937 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7938 goto create_error_entry;
7941 if (is_type_valid(type_left) && !saw_error) {
7943 "request for member '%Y' in something not a struct or union, but '%T'",
7947 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7950 assert(is_declaration(entry));
7951 select->select.compound_entry = entry;
7953 type_t *entry_type = entry->declaration.type;
7955 = get_qualified_type(entry_type, type_left->base.qualifiers);
7957 /* we always do the auto-type conversions; the & and sizeof parser contains
7958 * code to revert this! */
7959 select->base.type = automatic_type_conversion(res_type);
7961 type_t *skipped = skip_typeref(res_type);
7962 if (skipped->kind == TYPE_BITFIELD) {
7963 select->base.type = skipped->bitfield.base_type;
7969 static void check_call_argument(const function_parameter_t *parameter,
7970 call_argument_t *argument, unsigned pos)
7972 type_t *expected_type = parameter->type;
7973 type_t *expected_type_skip = skip_typeref(expected_type);
7974 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7975 expression_t *arg_expr = argument->expression;
7976 type_t *arg_type = skip_typeref(arg_expr->base.type);
7978 /* handle transparent union gnu extension */
7979 if (is_type_union(expected_type_skip)
7980 && (expected_type_skip->base.modifiers
7981 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7982 compound_t *union_decl = expected_type_skip->compound.compound;
7983 type_t *best_type = NULL;
7984 entity_t *entry = union_decl->members.entities;
7985 for ( ; entry != NULL; entry = entry->base.next) {
7986 assert(is_declaration(entry));
7987 type_t *decl_type = entry->declaration.type;
7988 error = semantic_assign(decl_type, arg_expr);
7989 if (error == ASSIGN_ERROR_INCOMPATIBLE
7990 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7993 if (error == ASSIGN_SUCCESS) {
7994 best_type = decl_type;
7995 } else if (best_type == NULL) {
7996 best_type = decl_type;
8000 if (best_type != NULL) {
8001 expected_type = best_type;
8005 error = semantic_assign(expected_type, arg_expr);
8006 argument->expression = create_implicit_cast(argument->expression,
8009 if (error != ASSIGN_SUCCESS) {
8010 /* report exact scope in error messages (like "in argument 3") */
8012 snprintf(buf, sizeof(buf), "call argument %u", pos);
8013 report_assign_error(error, expected_type, arg_expr, buf,
8014 &arg_expr->base.source_position);
8015 } else if (warning.traditional || warning.conversion) {
8016 type_t *const promoted_type = get_default_promoted_type(arg_type);
8017 if (!types_compatible(expected_type_skip, promoted_type) &&
8018 !types_compatible(expected_type_skip, type_void_ptr) &&
8019 !types_compatible(type_void_ptr, promoted_type)) {
8020 /* Deliberately show the skipped types in this warning */
8021 warningf(&arg_expr->base.source_position,
8022 "passing call argument %u as '%T' rather than '%T' due to prototype",
8023 pos, expected_type_skip, promoted_type);
8029 * Parse a call expression, ie. expression '( ... )'.
8031 * @param expression the function address
8033 static expression_t *parse_call_expression(expression_t *expression)
8035 expression_t *result = allocate_expression_zero(EXPR_CALL);
8036 call_expression_t *call = &result->call;
8037 call->function = expression;
8039 type_t *const orig_type = expression->base.type;
8040 type_t *const type = skip_typeref(orig_type);
8042 function_type_t *function_type = NULL;
8043 if (is_type_pointer(type)) {
8044 type_t *const to_type = skip_typeref(type->pointer.points_to);
8046 if (is_type_function(to_type)) {
8047 function_type = &to_type->function;
8048 call->base.type = function_type->return_type;
8052 if (function_type == NULL && is_type_valid(type)) {
8053 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
8056 /* parse arguments */
8058 add_anchor_token(')');
8059 add_anchor_token(',');
8061 if (token.type != ')') {
8062 call_argument_t *last_argument = NULL;
8065 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8067 argument->expression = parse_assignment_expression();
8068 if (last_argument == NULL) {
8069 call->arguments = argument;
8071 last_argument->next = argument;
8073 last_argument = argument;
8075 if (token.type != ',')
8080 rem_anchor_token(',');
8081 rem_anchor_token(')');
8084 if (function_type == NULL)
8087 function_parameter_t *parameter = function_type->parameters;
8088 call_argument_t *argument = call->arguments;
8089 if (!function_type->unspecified_parameters) {
8090 for (unsigned pos = 0; parameter != NULL && argument != NULL;
8091 parameter = parameter->next, argument = argument->next) {
8092 check_call_argument(parameter, argument, ++pos);
8095 if (parameter != NULL) {
8096 errorf(HERE, "too few arguments to function '%E'", expression);
8097 } else if (argument != NULL && !function_type->variadic) {
8098 errorf(HERE, "too many arguments to function '%E'", expression);
8102 /* do default promotion */
8103 for (; argument != NULL; argument = argument->next) {
8104 type_t *type = argument->expression->base.type;
8106 type = get_default_promoted_type(type);
8108 argument->expression
8109 = create_implicit_cast(argument->expression, type);
8112 check_format(&result->call);
8114 if (warning.aggregate_return &&
8115 is_type_compound(skip_typeref(function_type->return_type))) {
8116 warningf(&result->base.source_position,
8117 "function call has aggregate value");
8124 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
8126 static bool same_compound_type(const type_t *type1, const type_t *type2)
8129 is_type_compound(type1) &&
8130 type1->kind == type2->kind &&
8131 type1->compound.compound == type2->compound.compound;
8134 static expression_t const *get_reference_address(expression_t const *expr)
8136 bool regular_take_address = true;
8138 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8139 expr = expr->unary.value;
8141 regular_take_address = false;
8144 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8147 expr = expr->unary.value;
8150 if (expr->kind != EXPR_REFERENCE)
8153 /* special case for functions which are automatically converted to a
8154 * pointer to function without an extra TAKE_ADDRESS operation */
8155 if (!regular_take_address &&
8156 expr->reference.entity->kind != ENTITY_FUNCTION) {
8163 static void warn_reference_address_as_bool(expression_t const* expr)
8165 if (!warning.address)
8168 expr = get_reference_address(expr);
8170 warningf(&expr->base.source_position,
8171 "the address of '%Y' will always evaluate as 'true'",
8172 expr->reference.entity->base.symbol);
8176 static void semantic_condition(expression_t const *const expr,
8177 char const *const context)
8179 type_t *const type = skip_typeref(expr->base.type);
8180 if (is_type_scalar(type)) {
8181 warn_reference_address_as_bool(expr);
8182 } else if (is_type_valid(type)) {
8183 errorf(&expr->base.source_position,
8184 "%s must have scalar type", context);
8189 * Parse a conditional expression, ie. 'expression ? ... : ...'.
8191 * @param expression the conditional expression
8193 static expression_t *parse_conditional_expression(expression_t *expression)
8195 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
8197 conditional_expression_t *conditional = &result->conditional;
8198 conditional->condition = expression;
8201 add_anchor_token(':');
8203 /* §6.5.15:2 The first operand shall have scalar type. */
8204 semantic_condition(expression, "condition of conditional operator");
8206 expression_t *true_expression = expression;
8207 bool gnu_cond = false;
8208 if (GNU_MODE && token.type == ':') {
8211 true_expression = parse_expression();
8213 rem_anchor_token(':');
8215 expression_t *false_expression =
8216 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
8218 type_t *const orig_true_type = true_expression->base.type;
8219 type_t *const orig_false_type = false_expression->base.type;
8220 type_t *const true_type = skip_typeref(orig_true_type);
8221 type_t *const false_type = skip_typeref(orig_false_type);
8224 type_t *result_type;
8225 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8226 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
8227 /* ISO/IEC 14882:1998(E) §5.16:2 */
8228 if (true_expression->kind == EXPR_UNARY_THROW) {
8229 result_type = false_type;
8230 } else if (false_expression->kind == EXPR_UNARY_THROW) {
8231 result_type = true_type;
8233 if (warning.other && (
8234 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
8235 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8237 warningf(&conditional->base.source_position,
8238 "ISO C forbids conditional expression with only one void side");
8240 result_type = type_void;
8242 } else if (is_type_arithmetic(true_type)
8243 && is_type_arithmetic(false_type)) {
8244 result_type = semantic_arithmetic(true_type, false_type);
8246 true_expression = create_implicit_cast(true_expression, result_type);
8247 false_expression = create_implicit_cast(false_expression, result_type);
8249 conditional->true_expression = true_expression;
8250 conditional->false_expression = false_expression;
8251 conditional->base.type = result_type;
8252 } else if (same_compound_type(true_type, false_type)) {
8253 /* just take 1 of the 2 types */
8254 result_type = true_type;
8255 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8256 type_t *pointer_type;
8258 expression_t *other_expression;
8259 if (is_type_pointer(true_type) &&
8260 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8261 pointer_type = true_type;
8262 other_type = false_type;
8263 other_expression = false_expression;
8265 pointer_type = false_type;
8266 other_type = true_type;
8267 other_expression = true_expression;
8270 if (is_null_pointer_constant(other_expression)) {
8271 result_type = pointer_type;
8272 } else if (is_type_pointer(other_type)) {
8273 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8274 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8277 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8278 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8280 } else if (types_compatible(get_unqualified_type(to1),
8281 get_unqualified_type(to2))) {
8284 if (warning.other) {
8285 warningf(&conditional->base.source_position,
8286 "pointer types '%T' and '%T' in conditional expression are incompatible",
8287 true_type, false_type);
8292 type_t *const type =
8293 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8294 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8295 } else if (is_type_integer(other_type)) {
8296 if (warning.other) {
8297 warningf(&conditional->base.source_position,
8298 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8300 result_type = pointer_type;
8302 if (is_type_valid(other_type)) {
8303 type_error_incompatible("while parsing conditional",
8304 &expression->base.source_position, true_type, false_type);
8306 result_type = type_error_type;
8309 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8310 type_error_incompatible("while parsing conditional",
8311 &conditional->base.source_position, true_type,
8314 result_type = type_error_type;
8317 conditional->true_expression
8318 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8319 conditional->false_expression
8320 = create_implicit_cast(false_expression, result_type);
8321 conditional->base.type = result_type;
8324 return create_invalid_expression();
8328 * Parse an extension expression.
8330 static expression_t *parse_extension(void)
8332 eat(T___extension__);
8334 bool old_gcc_extension = in_gcc_extension;
8335 in_gcc_extension = true;
8336 expression_t *expression = parse_sub_expression(PREC_UNARY);
8337 in_gcc_extension = old_gcc_extension;
8342 * Parse a __builtin_classify_type() expression.
8344 static expression_t *parse_builtin_classify_type(void)
8346 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8347 result->base.type = type_int;
8349 eat(T___builtin_classify_type);
8352 add_anchor_token(')');
8353 expression_t *expression = parse_expression();
8354 rem_anchor_token(')');
8356 result->classify_type.type_expression = expression;
8360 return create_invalid_expression();
8364 * Parse a delete expression
8365 * ISO/IEC 14882:1998(E) §5.3.5
8367 static expression_t *parse_delete(void)
8369 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8370 result->base.type = type_void;
8374 if (token.type == '[') {
8376 result->kind = EXPR_UNARY_DELETE_ARRAY;
8381 expression_t *const value = parse_sub_expression(PREC_CAST);
8382 result->unary.value = value;
8384 type_t *const type = skip_typeref(value->base.type);
8385 if (!is_type_pointer(type)) {
8386 errorf(&value->base.source_position,
8387 "operand of delete must have pointer type");
8388 } else if (warning.other &&
8389 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8390 warningf(&value->base.source_position,
8391 "deleting 'void*' is undefined");
8398 * Parse a throw expression
8399 * ISO/IEC 14882:1998(E) §15:1
8401 static expression_t *parse_throw(void)
8403 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8404 result->base.type = type_void;
8408 expression_t *value = NULL;
8409 switch (token.type) {
8411 value = parse_assignment_expression();
8412 /* ISO/IEC 14882:1998(E) §15.1:3 */
8413 type_t *const orig_type = value->base.type;
8414 type_t *const type = skip_typeref(orig_type);
8415 if (is_type_incomplete(type)) {
8416 errorf(&value->base.source_position,
8417 "cannot throw object of incomplete type '%T'", orig_type);
8418 } else if (is_type_pointer(type)) {
8419 type_t *const points_to = skip_typeref(type->pointer.points_to);
8420 if (is_type_incomplete(points_to) &&
8421 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8422 errorf(&value->base.source_position,
8423 "cannot throw pointer to incomplete type '%T'", orig_type);
8431 result->unary.value = value;
8436 static bool check_pointer_arithmetic(const source_position_t *source_position,
8437 type_t *pointer_type,
8438 type_t *orig_pointer_type)
8440 type_t *points_to = pointer_type->pointer.points_to;
8441 points_to = skip_typeref(points_to);
8443 if (is_type_incomplete(points_to)) {
8444 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8445 errorf(source_position,
8446 "arithmetic with pointer to incomplete type '%T' not allowed",
8449 } else if (warning.pointer_arith) {
8450 warningf(source_position,
8451 "pointer of type '%T' used in arithmetic",
8454 } else if (is_type_function(points_to)) {
8456 errorf(source_position,
8457 "arithmetic with pointer to function type '%T' not allowed",
8460 } else if (warning.pointer_arith) {
8461 warningf(source_position,
8462 "pointer to a function '%T' used in arithmetic",
8469 static bool is_lvalue(const expression_t *expression)
8471 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8472 switch (expression->kind) {
8473 case EXPR_REFERENCE:
8474 case EXPR_ARRAY_ACCESS:
8476 case EXPR_UNARY_DEREFERENCE:
8480 type_t *type = skip_typeref(expression->base.type);
8482 /* ISO/IEC 14882:1998(E) §3.10:3 */
8483 is_type_reference(type) ||
8484 /* Claim it is an lvalue, if the type is invalid. There was a parse
8485 * error before, which maybe prevented properly recognizing it as
8487 !is_type_valid(type);
8492 static void semantic_incdec(unary_expression_t *expression)
8494 type_t *const orig_type = expression->value->base.type;
8495 type_t *const type = skip_typeref(orig_type);
8496 if (is_type_pointer(type)) {
8497 if (!check_pointer_arithmetic(&expression->base.source_position,
8501 } else if (!is_type_real(type) && is_type_valid(type)) {
8502 /* TODO: improve error message */
8503 errorf(&expression->base.source_position,
8504 "operation needs an arithmetic or pointer type");
8507 if (!is_lvalue(expression->value)) {
8508 /* TODO: improve error message */
8509 errorf(&expression->base.source_position, "lvalue required as operand");
8511 expression->base.type = orig_type;
8514 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8516 type_t *const orig_type = expression->value->base.type;
8517 type_t *const type = skip_typeref(orig_type);
8518 if (!is_type_arithmetic(type)) {
8519 if (is_type_valid(type)) {
8520 /* TODO: improve error message */
8521 errorf(&expression->base.source_position,
8522 "operation needs an arithmetic type");
8527 expression->base.type = orig_type;
8530 static void semantic_unexpr_plus(unary_expression_t *expression)
8532 semantic_unexpr_arithmetic(expression);
8533 if (warning.traditional)
8534 warningf(&expression->base.source_position,
8535 "traditional C rejects the unary plus operator");
8538 static void semantic_not(unary_expression_t *expression)
8540 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8541 semantic_condition(expression->value, "operand of !");
8542 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8545 static void semantic_unexpr_integer(unary_expression_t *expression)
8547 type_t *const orig_type = expression->value->base.type;
8548 type_t *const type = skip_typeref(orig_type);
8549 if (!is_type_integer(type)) {
8550 if (is_type_valid(type)) {
8551 errorf(&expression->base.source_position,
8552 "operand of ~ must be of integer type");
8557 expression->base.type = orig_type;
8560 static void semantic_dereference(unary_expression_t *expression)
8562 type_t *const orig_type = expression->value->base.type;
8563 type_t *const type = skip_typeref(orig_type);
8564 if (!is_type_pointer(type)) {
8565 if (is_type_valid(type)) {
8566 errorf(&expression->base.source_position,
8567 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8572 type_t *result_type = type->pointer.points_to;
8573 result_type = automatic_type_conversion(result_type);
8574 expression->base.type = result_type;
8578 * Record that an address is taken (expression represents an lvalue).
8580 * @param expression the expression
8581 * @param may_be_register if true, the expression might be an register
8583 static void set_address_taken(expression_t *expression, bool may_be_register)
8585 if (expression->kind != EXPR_REFERENCE)
8588 entity_t *const entity = expression->reference.entity;
8590 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8593 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8594 && !may_be_register) {
8595 errorf(&expression->base.source_position,
8596 "address of register %s '%Y' requested",
8597 get_entity_kind_name(entity->kind), entity->base.symbol);
8600 if (entity->kind == ENTITY_VARIABLE) {
8601 entity->variable.address_taken = true;
8603 assert(entity->kind == ENTITY_PARAMETER);
8604 entity->parameter.address_taken = true;
8609 * Check the semantic of the address taken expression.
8611 static void semantic_take_addr(unary_expression_t *expression)
8613 expression_t *value = expression->value;
8614 value->base.type = revert_automatic_type_conversion(value);
8616 type_t *orig_type = value->base.type;
8617 type_t *type = skip_typeref(orig_type);
8618 if (!is_type_valid(type))
8622 if (!is_lvalue(value)) {
8623 errorf(&expression->base.source_position, "'&' requires an lvalue");
8625 if (type->kind == TYPE_BITFIELD) {
8626 errorf(&expression->base.source_position,
8627 "'&' not allowed on object with bitfield type '%T'",
8631 set_address_taken(value, false);
8633 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8636 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8637 static expression_t *parse_##unexpression_type(void) \
8639 expression_t *unary_expression \
8640 = allocate_expression_zero(unexpression_type); \
8642 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8644 sfunc(&unary_expression->unary); \
8646 return unary_expression; \
8649 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8650 semantic_unexpr_arithmetic)
8651 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8652 semantic_unexpr_plus)
8653 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8655 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8656 semantic_dereference)
8657 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8659 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8660 semantic_unexpr_integer)
8661 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8663 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8666 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8668 static expression_t *parse_##unexpression_type(expression_t *left) \
8670 expression_t *unary_expression \
8671 = allocate_expression_zero(unexpression_type); \
8673 unary_expression->unary.value = left; \
8675 sfunc(&unary_expression->unary); \
8677 return unary_expression; \
8680 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8681 EXPR_UNARY_POSTFIX_INCREMENT,
8683 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8684 EXPR_UNARY_POSTFIX_DECREMENT,
8687 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8689 /* TODO: handle complex + imaginary types */
8691 type_left = get_unqualified_type(type_left);
8692 type_right = get_unqualified_type(type_right);
8694 /* § 6.3.1.8 Usual arithmetic conversions */
8695 if (type_left == type_long_double || type_right == type_long_double) {
8696 return type_long_double;
8697 } else if (type_left == type_double || type_right == type_double) {
8699 } else if (type_left == type_float || type_right == type_float) {
8703 type_left = promote_integer(type_left);
8704 type_right = promote_integer(type_right);
8706 if (type_left == type_right)
8709 bool const signed_left = is_type_signed(type_left);
8710 bool const signed_right = is_type_signed(type_right);
8711 int const rank_left = get_rank(type_left);
8712 int const rank_right = get_rank(type_right);
8714 if (signed_left == signed_right)
8715 return rank_left >= rank_right ? type_left : type_right;
8724 u_rank = rank_right;
8725 u_type = type_right;
8727 s_rank = rank_right;
8728 s_type = type_right;
8733 if (u_rank >= s_rank)
8736 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8738 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8739 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8743 case ATOMIC_TYPE_INT: return type_unsigned_int;
8744 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8745 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8747 default: panic("invalid atomic type");
8752 * Check the semantic restrictions for a binary expression.
8754 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8756 expression_t *const left = expression->left;
8757 expression_t *const right = expression->right;
8758 type_t *const orig_type_left = left->base.type;
8759 type_t *const orig_type_right = right->base.type;
8760 type_t *const type_left = skip_typeref(orig_type_left);
8761 type_t *const type_right = skip_typeref(orig_type_right);
8763 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8764 /* TODO: improve error message */
8765 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8766 errorf(&expression->base.source_position,
8767 "operation needs arithmetic types");
8772 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8773 expression->left = create_implicit_cast(left, arithmetic_type);
8774 expression->right = create_implicit_cast(right, arithmetic_type);
8775 expression->base.type = arithmetic_type;
8778 static void warn_div_by_zero(binary_expression_t const *const expression)
8780 if (!warning.div_by_zero ||
8781 !is_type_integer(expression->base.type))
8784 expression_t const *const right = expression->right;
8785 /* The type of the right operand can be different for /= */
8786 if (is_type_integer(right->base.type) &&
8787 is_constant_expression(right) &&
8788 fold_constant(right) == 0) {
8789 warningf(&expression->base.source_position, "division by zero");
8794 * Check the semantic restrictions for a div/mod expression.
8796 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8797 semantic_binexpr_arithmetic(expression);
8798 warn_div_by_zero(expression);
8801 static void semantic_shift_op(binary_expression_t *expression)
8803 expression_t *const left = expression->left;
8804 expression_t *const right = expression->right;
8805 type_t *const orig_type_left = left->base.type;
8806 type_t *const orig_type_right = right->base.type;
8807 type_t * type_left = skip_typeref(orig_type_left);
8808 type_t * type_right = skip_typeref(orig_type_right);
8810 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8811 /* TODO: improve error message */
8812 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8813 errorf(&expression->base.source_position,
8814 "operands of shift operation must have integer types");
8819 type_left = promote_integer(type_left);
8820 type_right = promote_integer(type_right);
8822 expression->left = create_implicit_cast(left, type_left);
8823 expression->right = create_implicit_cast(right, type_right);
8824 expression->base.type = type_left;
8827 static void semantic_add(binary_expression_t *expression)
8829 expression_t *const left = expression->left;
8830 expression_t *const right = expression->right;
8831 type_t *const orig_type_left = left->base.type;
8832 type_t *const orig_type_right = right->base.type;
8833 type_t *const type_left = skip_typeref(orig_type_left);
8834 type_t *const type_right = skip_typeref(orig_type_right);
8837 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8838 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8839 expression->left = create_implicit_cast(left, arithmetic_type);
8840 expression->right = create_implicit_cast(right, arithmetic_type);
8841 expression->base.type = arithmetic_type;
8843 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8844 check_pointer_arithmetic(&expression->base.source_position,
8845 type_left, orig_type_left);
8846 expression->base.type = type_left;
8847 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8848 check_pointer_arithmetic(&expression->base.source_position,
8849 type_right, orig_type_right);
8850 expression->base.type = type_right;
8851 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8852 errorf(&expression->base.source_position,
8853 "invalid operands to binary + ('%T', '%T')",
8854 orig_type_left, orig_type_right);
8858 static void semantic_sub(binary_expression_t *expression)
8860 expression_t *const left = expression->left;
8861 expression_t *const right = expression->right;
8862 type_t *const orig_type_left = left->base.type;
8863 type_t *const orig_type_right = right->base.type;
8864 type_t *const type_left = skip_typeref(orig_type_left);
8865 type_t *const type_right = skip_typeref(orig_type_right);
8866 source_position_t const *const pos = &expression->base.source_position;
8869 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8870 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8871 expression->left = create_implicit_cast(left, arithmetic_type);
8872 expression->right = create_implicit_cast(right, arithmetic_type);
8873 expression->base.type = arithmetic_type;
8875 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8876 check_pointer_arithmetic(&expression->base.source_position,
8877 type_left, orig_type_left);
8878 expression->base.type = type_left;
8879 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8880 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8881 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8882 if (!types_compatible(unqual_left, unqual_right)) {
8884 "subtracting pointers to incompatible types '%T' and '%T'",
8885 orig_type_left, orig_type_right);
8886 } else if (!is_type_object(unqual_left)) {
8887 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8888 errorf(pos, "subtracting pointers to non-object types '%T'",
8890 } else if (warning.other) {
8891 warningf(pos, "subtracting pointers to void");
8894 expression->base.type = type_ptrdiff_t;
8895 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8896 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8897 orig_type_left, orig_type_right);
8901 static void warn_string_literal_address(expression_t const* expr)
8903 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8904 expr = expr->unary.value;
8905 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8907 expr = expr->unary.value;
8910 if (expr->kind == EXPR_STRING_LITERAL ||
8911 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8912 warningf(&expr->base.source_position,
8913 "comparison with string literal results in unspecified behaviour");
8918 * Check the semantics of comparison expressions.
8920 * @param expression The expression to check.
8922 static void semantic_comparison(binary_expression_t *expression)
8924 expression_t *left = expression->left;
8925 expression_t *right = expression->right;
8927 if (warning.address) {
8928 warn_string_literal_address(left);
8929 warn_string_literal_address(right);
8931 expression_t const* const func_left = get_reference_address(left);
8932 if (func_left != NULL && is_null_pointer_constant(right)) {
8933 warningf(&expression->base.source_position,
8934 "the address of '%Y' will never be NULL",
8935 func_left->reference.entity->base.symbol);
8938 expression_t const* const func_right = get_reference_address(right);
8939 if (func_right != NULL && is_null_pointer_constant(right)) {
8940 warningf(&expression->base.source_position,
8941 "the address of '%Y' will never be NULL",
8942 func_right->reference.entity->base.symbol);
8946 type_t *orig_type_left = left->base.type;
8947 type_t *orig_type_right = right->base.type;
8948 type_t *type_left = skip_typeref(orig_type_left);
8949 type_t *type_right = skip_typeref(orig_type_right);
8951 /* TODO non-arithmetic types */
8952 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8953 /* test for signed vs unsigned compares */
8954 if (warning.sign_compare &&
8955 (expression->base.kind != EXPR_BINARY_EQUAL &&
8956 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8957 (is_type_signed(type_left) != is_type_signed(type_right))) {
8959 /* check if 1 of the operands is a constant, in this case we just
8960 * check wether we can safely represent the resulting constant in
8961 * the type of the other operand. */
8962 expression_t *const_expr = NULL;
8963 expression_t *other_expr = NULL;
8965 if (is_constant_expression(left)) {
8968 } else if (is_constant_expression(right)) {
8973 if (const_expr != NULL) {
8974 type_t *other_type = skip_typeref(other_expr->base.type);
8975 long val = fold_constant(const_expr);
8976 /* TODO: check if val can be represented by other_type */
8980 warningf(&expression->base.source_position,
8981 "comparison between signed and unsigned");
8983 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8984 expression->left = create_implicit_cast(left, arithmetic_type);
8985 expression->right = create_implicit_cast(right, arithmetic_type);
8986 expression->base.type = arithmetic_type;
8987 if (warning.float_equal &&
8988 (expression->base.kind == EXPR_BINARY_EQUAL ||
8989 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8990 is_type_float(arithmetic_type)) {
8991 warningf(&expression->base.source_position,
8992 "comparing floating point with == or != is unsafe");
8994 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8995 /* TODO check compatibility */
8996 } else if (is_type_pointer(type_left)) {
8997 expression->right = create_implicit_cast(right, type_left);
8998 } else if (is_type_pointer(type_right)) {
8999 expression->left = create_implicit_cast(left, type_right);
9000 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9001 type_error_incompatible("invalid operands in comparison",
9002 &expression->base.source_position,
9003 type_left, type_right);
9005 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9009 * Checks if a compound type has constant fields.
9011 static bool has_const_fields(const compound_type_t *type)
9013 compound_t *compound = type->compound;
9014 entity_t *entry = compound->members.entities;
9016 for (; entry != NULL; entry = entry->base.next) {
9017 if (!is_declaration(entry))
9020 const type_t *decl_type = skip_typeref(entry->declaration.type);
9021 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
9028 static bool is_valid_assignment_lhs(expression_t const* const left)
9030 type_t *const orig_type_left = revert_automatic_type_conversion(left);
9031 type_t *const type_left = skip_typeref(orig_type_left);
9033 if (!is_lvalue(left)) {
9034 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
9039 if (left->kind == EXPR_REFERENCE
9040 && left->reference.entity->kind == ENTITY_FUNCTION) {
9041 errorf(HERE, "cannot assign to function '%E'", left);
9045 if (is_type_array(type_left)) {
9046 errorf(HERE, "cannot assign to array '%E'", left);
9049 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
9050 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
9054 if (is_type_incomplete(type_left)) {
9055 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
9056 left, orig_type_left);
9059 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
9060 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
9061 left, orig_type_left);
9068 static void semantic_arithmetic_assign(binary_expression_t *expression)
9070 expression_t *left = expression->left;
9071 expression_t *right = expression->right;
9072 type_t *orig_type_left = left->base.type;
9073 type_t *orig_type_right = right->base.type;
9075 if (!is_valid_assignment_lhs(left))
9078 type_t *type_left = skip_typeref(orig_type_left);
9079 type_t *type_right = skip_typeref(orig_type_right);
9081 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
9082 /* TODO: improve error message */
9083 if (is_type_valid(type_left) && is_type_valid(type_right)) {
9084 errorf(&expression->base.source_position,
9085 "operation needs arithmetic types");
9090 /* combined instructions are tricky. We can't create an implicit cast on
9091 * the left side, because we need the uncasted form for the store.
9092 * The ast2firm pass has to know that left_type must be right_type
9093 * for the arithmetic operation and create a cast by itself */
9094 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
9095 expression->right = create_implicit_cast(right, arithmetic_type);
9096 expression->base.type = type_left;
9099 static void semantic_divmod_assign(binary_expression_t *expression)
9101 semantic_arithmetic_assign(expression);
9102 warn_div_by_zero(expression);
9105 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
9107 expression_t *const left = expression->left;
9108 expression_t *const right = expression->right;
9109 type_t *const orig_type_left = left->base.type;
9110 type_t *const orig_type_right = right->base.type;
9111 type_t *const type_left = skip_typeref(orig_type_left);
9112 type_t *const type_right = skip_typeref(orig_type_right);
9114 if (!is_valid_assignment_lhs(left))
9117 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
9118 /* combined instructions are tricky. We can't create an implicit cast on
9119 * the left side, because we need the uncasted form for the store.
9120 * The ast2firm pass has to know that left_type must be right_type
9121 * for the arithmetic operation and create a cast by itself */
9122 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
9123 expression->right = create_implicit_cast(right, arithmetic_type);
9124 expression->base.type = type_left;
9125 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
9126 check_pointer_arithmetic(&expression->base.source_position,
9127 type_left, orig_type_left);
9128 expression->base.type = type_left;
9129 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
9130 errorf(&expression->base.source_position,
9131 "incompatible types '%T' and '%T' in assignment",
9132 orig_type_left, orig_type_right);
9137 * Check the semantic restrictions of a logical expression.
9139 static void semantic_logical_op(binary_expression_t *expression)
9141 /* §6.5.13:2 Each of the operands shall have scalar type.
9142 * §6.5.14:2 Each of the operands shall have scalar type. */
9143 semantic_condition(expression->left, "left operand of logical operator");
9144 semantic_condition(expression->right, "right operand of logical operator");
9145 expression->base.type = c_mode & _CXX ? type_bool : type_int;
9149 * Check the semantic restrictions of a binary assign expression.
9151 static void semantic_binexpr_assign(binary_expression_t *expression)
9153 expression_t *left = expression->left;
9154 type_t *orig_type_left = left->base.type;
9156 if (!is_valid_assignment_lhs(left))
9159 assign_error_t error = semantic_assign(orig_type_left, expression->right);
9160 report_assign_error(error, orig_type_left, expression->right,
9161 "assignment", &left->base.source_position);
9162 expression->right = create_implicit_cast(expression->right, orig_type_left);
9163 expression->base.type = orig_type_left;
9167 * Determine if the outermost operation (or parts thereof) of the given
9168 * expression has no effect in order to generate a warning about this fact.
9169 * Therefore in some cases this only examines some of the operands of the
9170 * expression (see comments in the function and examples below).
9172 * f() + 23; // warning, because + has no effect
9173 * x || f(); // no warning, because x controls execution of f()
9174 * x ? y : f(); // warning, because y has no effect
9175 * (void)x; // no warning to be able to suppress the warning
9176 * This function can NOT be used for an "expression has definitely no effect"-
9178 static bool expression_has_effect(const expression_t *const expr)
9180 switch (expr->kind) {
9181 case EXPR_UNKNOWN: break;
9182 case EXPR_INVALID: return true; /* do NOT warn */
9183 case EXPR_REFERENCE: return false;
9184 case EXPR_REFERENCE_ENUM_VALUE: return false;
9185 /* suppress the warning for microsoft __noop operations */
9186 case EXPR_CONST: return expr->conste.is_ms_noop;
9187 case EXPR_CHARACTER_CONSTANT: return false;
9188 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
9189 case EXPR_STRING_LITERAL: return false;
9190 case EXPR_WIDE_STRING_LITERAL: return false;
9191 case EXPR_LABEL_ADDRESS: return false;
9194 const call_expression_t *const call = &expr->call;
9195 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
9198 switch (call->function->builtin_symbol.symbol->ID) {
9199 case T___builtin_va_end: return true;
9200 default: return false;
9204 /* Generate the warning if either the left or right hand side of a
9205 * conditional expression has no effect */
9206 case EXPR_CONDITIONAL: {
9207 const conditional_expression_t *const cond = &expr->conditional;
9209 expression_has_effect(cond->true_expression) &&
9210 expression_has_effect(cond->false_expression);
9213 case EXPR_SELECT: return false;
9214 case EXPR_ARRAY_ACCESS: return false;
9215 case EXPR_SIZEOF: return false;
9216 case EXPR_CLASSIFY_TYPE: return false;
9217 case EXPR_ALIGNOF: return false;
9219 case EXPR_FUNCNAME: return false;
9220 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
9221 case EXPR_BUILTIN_CONSTANT_P: return false;
9222 case EXPR_BUILTIN_PREFETCH: return true;
9223 case EXPR_OFFSETOF: return false;
9224 case EXPR_VA_START: return true;
9225 case EXPR_VA_ARG: return true;
9226 case EXPR_STATEMENT: return true; // TODO
9227 case EXPR_COMPOUND_LITERAL: return false;
9229 case EXPR_UNARY_NEGATE: return false;
9230 case EXPR_UNARY_PLUS: return false;
9231 case EXPR_UNARY_BITWISE_NEGATE: return false;
9232 case EXPR_UNARY_NOT: return false;
9233 case EXPR_UNARY_DEREFERENCE: return false;
9234 case EXPR_UNARY_TAKE_ADDRESS: return false;
9235 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
9236 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
9237 case EXPR_UNARY_PREFIX_INCREMENT: return true;
9238 case EXPR_UNARY_PREFIX_DECREMENT: return true;
9240 /* Treat void casts as if they have an effect in order to being able to
9241 * suppress the warning */
9242 case EXPR_UNARY_CAST: {
9243 type_t *const type = skip_typeref(expr->base.type);
9244 return is_type_atomic(type, ATOMIC_TYPE_VOID);
9247 case EXPR_UNARY_CAST_IMPLICIT: return true;
9248 case EXPR_UNARY_ASSUME: return true;
9249 case EXPR_UNARY_DELETE: return true;
9250 case EXPR_UNARY_DELETE_ARRAY: return true;
9251 case EXPR_UNARY_THROW: return true;
9253 case EXPR_BINARY_ADD: return false;
9254 case EXPR_BINARY_SUB: return false;
9255 case EXPR_BINARY_MUL: return false;
9256 case EXPR_BINARY_DIV: return false;
9257 case EXPR_BINARY_MOD: return false;
9258 case EXPR_BINARY_EQUAL: return false;
9259 case EXPR_BINARY_NOTEQUAL: return false;
9260 case EXPR_BINARY_LESS: return false;
9261 case EXPR_BINARY_LESSEQUAL: return false;
9262 case EXPR_BINARY_GREATER: return false;
9263 case EXPR_BINARY_GREATEREQUAL: return false;
9264 case EXPR_BINARY_BITWISE_AND: return false;
9265 case EXPR_BINARY_BITWISE_OR: return false;
9266 case EXPR_BINARY_BITWISE_XOR: return false;
9267 case EXPR_BINARY_SHIFTLEFT: return false;
9268 case EXPR_BINARY_SHIFTRIGHT: return false;
9269 case EXPR_BINARY_ASSIGN: return true;
9270 case EXPR_BINARY_MUL_ASSIGN: return true;
9271 case EXPR_BINARY_DIV_ASSIGN: return true;
9272 case EXPR_BINARY_MOD_ASSIGN: return true;
9273 case EXPR_BINARY_ADD_ASSIGN: return true;
9274 case EXPR_BINARY_SUB_ASSIGN: return true;
9275 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9276 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9277 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9278 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9279 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9281 /* Only examine the right hand side of && and ||, because the left hand
9282 * side already has the effect of controlling the execution of the right
9284 case EXPR_BINARY_LOGICAL_AND:
9285 case EXPR_BINARY_LOGICAL_OR:
9286 /* Only examine the right hand side of a comma expression, because the left
9287 * hand side has a separate warning */
9288 case EXPR_BINARY_COMMA:
9289 return expression_has_effect(expr->binary.right);
9291 case EXPR_BINARY_ISGREATER: return false;
9292 case EXPR_BINARY_ISGREATEREQUAL: return false;
9293 case EXPR_BINARY_ISLESS: return false;
9294 case EXPR_BINARY_ISLESSEQUAL: return false;
9295 case EXPR_BINARY_ISLESSGREATER: return false;
9296 case EXPR_BINARY_ISUNORDERED: return false;
9299 internal_errorf(HERE, "unexpected expression");
9302 static void semantic_comma(binary_expression_t *expression)
9304 if (warning.unused_value) {
9305 const expression_t *const left = expression->left;
9306 if (!expression_has_effect(left)) {
9307 warningf(&left->base.source_position,
9308 "left-hand operand of comma expression has no effect");
9311 expression->base.type = expression->right->base.type;
9315 * @param prec_r precedence of the right operand
9317 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9318 static expression_t *parse_##binexpression_type(expression_t *left) \
9320 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9321 binexpr->binary.left = left; \
9324 expression_t *right = parse_sub_expression(prec_r); \
9326 binexpr->binary.right = right; \
9327 sfunc(&binexpr->binary); \
9332 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9333 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9334 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9335 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9336 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9337 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9338 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9339 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9340 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9341 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9342 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9343 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9344 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9345 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9346 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9347 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9348 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9349 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9350 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9351 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9352 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9353 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9354 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9355 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9356 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9357 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9358 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9359 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9360 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9361 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9364 static expression_t *parse_sub_expression(precedence_t precedence)
9366 if (token.type < 0) {
9367 return expected_expression_error();
9370 expression_parser_function_t *parser
9371 = &expression_parsers[token.type];
9372 source_position_t source_position = token.source_position;
9375 if (parser->parser != NULL) {
9376 left = parser->parser();
9378 left = parse_primary_expression();
9380 assert(left != NULL);
9381 left->base.source_position = source_position;
9384 if (token.type < 0) {
9385 return expected_expression_error();
9388 parser = &expression_parsers[token.type];
9389 if (parser->infix_parser == NULL)
9391 if (parser->infix_precedence < precedence)
9394 left = parser->infix_parser(left);
9396 assert(left != NULL);
9397 assert(left->kind != EXPR_UNKNOWN);
9398 left->base.source_position = source_position;
9405 * Parse an expression.
9407 static expression_t *parse_expression(void)
9409 return parse_sub_expression(PREC_EXPRESSION);
9413 * Register a parser for a prefix-like operator.
9415 * @param parser the parser function
9416 * @param token_type the token type of the prefix token
9418 static void register_expression_parser(parse_expression_function parser,
9421 expression_parser_function_t *entry = &expression_parsers[token_type];
9423 if (entry->parser != NULL) {
9424 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9425 panic("trying to register multiple expression parsers for a token");
9427 entry->parser = parser;
9431 * Register a parser for an infix operator with given precedence.
9433 * @param parser the parser function
9434 * @param token_type the token type of the infix operator
9435 * @param precedence the precedence of the operator
9437 static void register_infix_parser(parse_expression_infix_function parser,
9438 int token_type, unsigned precedence)
9440 expression_parser_function_t *entry = &expression_parsers[token_type];
9442 if (entry->infix_parser != NULL) {
9443 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9444 panic("trying to register multiple infix expression parsers for a "
9447 entry->infix_parser = parser;
9448 entry->infix_precedence = precedence;
9452 * Initialize the expression parsers.
9454 static void init_expression_parsers(void)
9456 memset(&expression_parsers, 0, sizeof(expression_parsers));
9458 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9459 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9460 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9461 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9462 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9463 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9464 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9465 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9466 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9467 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9468 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9469 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9470 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9471 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9472 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9473 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9474 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9475 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9476 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9477 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9478 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9479 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9480 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9481 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9482 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9483 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9484 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9485 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9486 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9487 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9488 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9489 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9490 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9491 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9492 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9493 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9494 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9496 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9497 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9498 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9499 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9500 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9501 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9502 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9503 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9504 register_expression_parser(parse_sizeof, T_sizeof);
9505 register_expression_parser(parse_alignof, T___alignof__);
9506 register_expression_parser(parse_extension, T___extension__);
9507 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9508 register_expression_parser(parse_delete, T_delete);
9509 register_expression_parser(parse_throw, T_throw);
9513 * Parse a asm statement arguments specification.
9515 static asm_argument_t *parse_asm_arguments(bool is_out)
9517 asm_argument_t *result = NULL;
9518 asm_argument_t **anchor = &result;
9520 while (token.type == T_STRING_LITERAL || token.type == '[') {
9521 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9522 memset(argument, 0, sizeof(argument[0]));
9524 if (token.type == '[') {
9526 if (token.type != T_IDENTIFIER) {
9527 parse_error_expected("while parsing asm argument",
9528 T_IDENTIFIER, NULL);
9531 argument->symbol = token.v.symbol;
9536 argument->constraints = parse_string_literals();
9538 add_anchor_token(')');
9539 expression_t *expression = parse_expression();
9540 rem_anchor_token(')');
9542 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9543 * change size or type representation (e.g. int -> long is ok, but
9544 * int -> float is not) */
9545 if (expression->kind == EXPR_UNARY_CAST) {
9546 type_t *const type = expression->base.type;
9547 type_kind_t const kind = type->kind;
9548 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9551 if (kind == TYPE_ATOMIC) {
9552 atomic_type_kind_t const akind = type->atomic.akind;
9553 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9554 size = get_atomic_type_size(akind);
9556 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9557 size = get_atomic_type_size(get_intptr_kind());
9561 expression_t *const value = expression->unary.value;
9562 type_t *const value_type = value->base.type;
9563 type_kind_t const value_kind = value_type->kind;
9565 unsigned value_flags;
9566 unsigned value_size;
9567 if (value_kind == TYPE_ATOMIC) {
9568 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9569 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9570 value_size = get_atomic_type_size(value_akind);
9571 } else if (value_kind == TYPE_POINTER) {
9572 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9573 value_size = get_atomic_type_size(get_intptr_kind());
9578 if (value_flags != flags || value_size != size)
9582 } while (expression->kind == EXPR_UNARY_CAST);
9586 if (!is_lvalue(expression)) {
9587 errorf(&expression->base.source_position,
9588 "asm output argument is not an lvalue");
9591 if (argument->constraints.begin[0] == '+')
9592 mark_vars_read(expression, NULL);
9594 mark_vars_read(expression, NULL);
9596 argument->expression = expression;
9599 set_address_taken(expression, true);
9602 anchor = &argument->next;
9604 if (token.type != ',')
9615 * Parse a asm statement clobber specification.
9617 static asm_clobber_t *parse_asm_clobbers(void)
9619 asm_clobber_t *result = NULL;
9620 asm_clobber_t *last = NULL;
9622 while (token.type == T_STRING_LITERAL) {
9623 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9624 clobber->clobber = parse_string_literals();
9627 last->next = clobber;
9633 if (token.type != ',')
9642 * Parse an asm statement.
9644 static statement_t *parse_asm_statement(void)
9646 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9647 asm_statement_t *asm_statement = &statement->asms;
9651 if (token.type == T_volatile) {
9653 asm_statement->is_volatile = true;
9657 add_anchor_token(')');
9658 add_anchor_token(':');
9659 asm_statement->asm_text = parse_string_literals();
9661 if (token.type != ':') {
9662 rem_anchor_token(':');
9667 asm_statement->outputs = parse_asm_arguments(true);
9668 if (token.type != ':') {
9669 rem_anchor_token(':');
9674 asm_statement->inputs = parse_asm_arguments(false);
9675 if (token.type != ':') {
9676 rem_anchor_token(':');
9679 rem_anchor_token(':');
9682 asm_statement->clobbers = parse_asm_clobbers();
9685 rem_anchor_token(')');
9689 if (asm_statement->outputs == NULL) {
9690 /* GCC: An 'asm' instruction without any output operands will be treated
9691 * identically to a volatile 'asm' instruction. */
9692 asm_statement->is_volatile = true;
9697 return create_invalid_statement();
9701 * Parse a case statement.
9703 static statement_t *parse_case_statement(void)
9705 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9706 source_position_t *const pos = &statement->base.source_position;
9710 expression_t *const expression = parse_expression();
9711 statement->case_label.expression = expression;
9712 if (!is_constant_expression(expression)) {
9713 /* This check does not prevent the error message in all cases of an
9714 * prior error while parsing the expression. At least it catches the
9715 * common case of a mistyped enum entry. */
9716 if (is_type_valid(skip_typeref(expression->base.type))) {
9717 errorf(pos, "case label does not reduce to an integer constant");
9719 statement->case_label.is_bad = true;
9721 long const val = fold_constant(expression);
9722 statement->case_label.first_case = val;
9723 statement->case_label.last_case = val;
9727 if (token.type == T_DOTDOTDOT) {
9729 expression_t *const end_range = parse_expression();
9730 statement->case_label.end_range = end_range;
9731 if (!is_constant_expression(end_range)) {
9732 /* This check does not prevent the error message in all cases of an
9733 * prior error while parsing the expression. At least it catches the
9734 * common case of a mistyped enum entry. */
9735 if (is_type_valid(skip_typeref(end_range->base.type))) {
9736 errorf(pos, "case range does not reduce to an integer constant");
9738 statement->case_label.is_bad = true;
9740 long const val = fold_constant(end_range);
9741 statement->case_label.last_case = val;
9743 if (warning.other && val < statement->case_label.first_case) {
9744 statement->case_label.is_empty_range = true;
9745 warningf(pos, "empty range specified");
9751 PUSH_PARENT(statement);
9756 if (current_switch != NULL) {
9757 if (! statement->case_label.is_bad) {
9758 /* Check for duplicate case values */
9759 case_label_statement_t *c = &statement->case_label;
9760 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9761 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9764 if (c->last_case < l->first_case || c->first_case > l->last_case)
9767 errorf(pos, "duplicate case value (previously used %P)",
9768 &l->base.source_position);
9772 /* link all cases into the switch statement */
9773 if (current_switch->last_case == NULL) {
9774 current_switch->first_case = &statement->case_label;
9776 current_switch->last_case->next = &statement->case_label;
9778 current_switch->last_case = &statement->case_label;
9780 errorf(pos, "case label not within a switch statement");
9783 statement_t *const inner_stmt = parse_statement();
9784 statement->case_label.statement = inner_stmt;
9785 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9786 errorf(&inner_stmt->base.source_position, "declaration after case label");
9794 * Parse a default statement.
9796 static statement_t *parse_default_statement(void)
9798 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9802 PUSH_PARENT(statement);
9805 if (current_switch != NULL) {
9806 const case_label_statement_t *def_label = current_switch->default_label;
9807 if (def_label != NULL) {
9808 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9809 &def_label->base.source_position);
9811 current_switch->default_label = &statement->case_label;
9813 /* link all cases into the switch statement */
9814 if (current_switch->last_case == NULL) {
9815 current_switch->first_case = &statement->case_label;
9817 current_switch->last_case->next = &statement->case_label;
9819 current_switch->last_case = &statement->case_label;
9822 errorf(&statement->base.source_position,
9823 "'default' label not within a switch statement");
9826 statement_t *const inner_stmt = parse_statement();
9827 statement->case_label.statement = inner_stmt;
9828 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9829 errorf(&inner_stmt->base.source_position, "declaration after default label");
9836 return create_invalid_statement();
9840 * Parse a label statement.
9842 static statement_t *parse_label_statement(void)
9844 assert(token.type == T_IDENTIFIER);
9845 symbol_t *symbol = token.v.symbol;
9846 label_t *label = get_label(symbol);
9848 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9849 statement->label.label = label;
9853 PUSH_PARENT(statement);
9855 /* if statement is already set then the label is defined twice,
9856 * otherwise it was just mentioned in a goto/local label declaration so far
9858 if (label->statement != NULL) {
9859 errorf(HERE, "duplicate label '%Y' (declared %P)",
9860 symbol, &label->base.source_position);
9862 label->base.source_position = token.source_position;
9863 label->statement = statement;
9868 if (token.type == '}') {
9869 /* TODO only warn? */
9870 if (warning.other && false) {
9871 warningf(HERE, "label at end of compound statement");
9872 statement->label.statement = create_empty_statement();
9874 errorf(HERE, "label at end of compound statement");
9875 statement->label.statement = create_invalid_statement();
9877 } else if (token.type == ';') {
9878 /* Eat an empty statement here, to avoid the warning about an empty
9879 * statement after a label. label:; is commonly used to have a label
9880 * before a closing brace. */
9881 statement->label.statement = create_empty_statement();
9884 statement_t *const inner_stmt = parse_statement();
9885 statement->label.statement = inner_stmt;
9886 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9887 errorf(&inner_stmt->base.source_position, "declaration after label");
9891 /* remember the labels in a list for later checking */
9892 *label_anchor = &statement->label;
9893 label_anchor = &statement->label.next;
9900 * Parse an if statement.
9902 static statement_t *parse_if(void)
9904 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9908 PUSH_PARENT(statement);
9910 add_anchor_token('{');
9913 add_anchor_token(')');
9914 expression_t *const expr = parse_expression();
9915 statement->ifs.condition = expr;
9916 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9918 semantic_condition(expr, "condition of 'if'-statment");
9919 mark_vars_read(expr, NULL);
9920 rem_anchor_token(')');
9924 rem_anchor_token('{');
9926 add_anchor_token(T_else);
9927 statement->ifs.true_statement = parse_statement();
9928 rem_anchor_token(T_else);
9930 if (token.type == T_else) {
9932 statement->ifs.false_statement = parse_statement();
9940 * Check that all enums are handled in a switch.
9942 * @param statement the switch statement to check
9944 static void check_enum_cases(const switch_statement_t *statement) {
9945 const type_t *type = skip_typeref(statement->expression->base.type);
9946 if (! is_type_enum(type))
9948 const enum_type_t *enumt = &type->enumt;
9950 /* if we have a default, no warnings */
9951 if (statement->default_label != NULL)
9954 /* FIXME: calculation of value should be done while parsing */
9955 /* TODO: quadratic algorithm here. Change to an n log n one */
9956 long last_value = -1;
9957 const entity_t *entry = enumt->enume->base.next;
9958 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9959 entry = entry->base.next) {
9960 const expression_t *expression = entry->enum_value.value;
9961 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9963 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9964 if (l->expression == NULL)
9966 if (l->first_case <= value && value <= l->last_case) {
9972 warningf(&statement->base.source_position,
9973 "enumeration value '%Y' not handled in switch",
9974 entry->base.symbol);
9981 * Parse a switch statement.
9983 static statement_t *parse_switch(void)
9985 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9989 PUSH_PARENT(statement);
9992 add_anchor_token(')');
9993 expression_t *const expr = parse_expression();
9994 mark_vars_read(expr, NULL);
9995 type_t * type = skip_typeref(expr->base.type);
9996 if (is_type_integer(type)) {
9997 type = promote_integer(type);
9998 if (warning.traditional) {
9999 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
10000 warningf(&expr->base.source_position,
10001 "'%T' switch expression not converted to '%T' in ISO C",
10005 } else if (is_type_valid(type)) {
10006 errorf(&expr->base.source_position,
10007 "switch quantity is not an integer, but '%T'", type);
10008 type = type_error_type;
10010 statement->switchs.expression = create_implicit_cast(expr, type);
10012 rem_anchor_token(')');
10014 switch_statement_t *rem = current_switch;
10015 current_switch = &statement->switchs;
10016 statement->switchs.body = parse_statement();
10017 current_switch = rem;
10019 if (warning.switch_default &&
10020 statement->switchs.default_label == NULL) {
10021 warningf(&statement->base.source_position, "switch has no default case");
10023 if (warning.switch_enum)
10024 check_enum_cases(&statement->switchs);
10030 return create_invalid_statement();
10033 static statement_t *parse_loop_body(statement_t *const loop)
10035 statement_t *const rem = current_loop;
10036 current_loop = loop;
10038 statement_t *const body = parse_statement();
10040 current_loop = rem;
10045 * Parse a while statement.
10047 static statement_t *parse_while(void)
10049 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
10053 PUSH_PARENT(statement);
10056 add_anchor_token(')');
10057 expression_t *const cond = parse_expression();
10058 statement->whiles.condition = cond;
10059 /* §6.8.5:2 The controlling expression of an iteration statement shall
10060 * have scalar type. */
10061 semantic_condition(cond, "condition of 'while'-statement");
10062 mark_vars_read(cond, NULL);
10063 rem_anchor_token(')');
10066 statement->whiles.body = parse_loop_body(statement);
10072 return create_invalid_statement();
10076 * Parse a do statement.
10078 static statement_t *parse_do(void)
10080 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
10084 PUSH_PARENT(statement);
10086 add_anchor_token(T_while);
10087 statement->do_while.body = parse_loop_body(statement);
10088 rem_anchor_token(T_while);
10092 add_anchor_token(')');
10093 expression_t *const cond = parse_expression();
10094 statement->do_while.condition = cond;
10095 /* §6.8.5:2 The controlling expression of an iteration statement shall
10096 * have scalar type. */
10097 semantic_condition(cond, "condition of 'do-while'-statement");
10098 mark_vars_read(cond, NULL);
10099 rem_anchor_token(')');
10107 return create_invalid_statement();
10111 * Parse a for statement.
10113 static statement_t *parse_for(void)
10115 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
10119 PUSH_PARENT(statement);
10121 size_t const top = environment_top();
10122 scope_t *old_scope = scope_push(&statement->fors.scope);
10125 add_anchor_token(')');
10127 if (token.type == ';') {
10129 } else if (is_declaration_specifier(&token, false)) {
10130 parse_declaration(record_entity, DECL_FLAGS_NONE);
10132 add_anchor_token(';');
10133 expression_t *const init = parse_expression();
10134 statement->fors.initialisation = init;
10135 mark_vars_read(init, ENT_ANY);
10136 if (warning.unused_value && !expression_has_effect(init)) {
10137 warningf(&init->base.source_position,
10138 "initialisation of 'for'-statement has no effect");
10140 rem_anchor_token(';');
10144 if (token.type != ';') {
10145 add_anchor_token(';');
10146 expression_t *const cond = parse_expression();
10147 statement->fors.condition = cond;
10148 /* §6.8.5:2 The controlling expression of an iteration statement
10149 * shall have scalar type. */
10150 semantic_condition(cond, "condition of 'for'-statement");
10151 mark_vars_read(cond, NULL);
10152 rem_anchor_token(';');
10155 if (token.type != ')') {
10156 expression_t *const step = parse_expression();
10157 statement->fors.step = step;
10158 mark_vars_read(step, ENT_ANY);
10159 if (warning.unused_value && !expression_has_effect(step)) {
10160 warningf(&step->base.source_position,
10161 "step of 'for'-statement has no effect");
10165 rem_anchor_token(')');
10166 statement->fors.body = parse_loop_body(statement);
10168 assert(current_scope == &statement->fors.scope);
10169 scope_pop(old_scope);
10170 environment_pop_to(top);
10177 rem_anchor_token(')');
10178 assert(current_scope == &statement->fors.scope);
10179 scope_pop(old_scope);
10180 environment_pop_to(top);
10182 return create_invalid_statement();
10186 * Parse a goto statement.
10188 static statement_t *parse_goto(void)
10190 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
10193 if (GNU_MODE && token.type == '*') {
10195 expression_t *expression = parse_expression();
10196 mark_vars_read(expression, NULL);
10198 /* Argh: although documentation says the expression must be of type void*,
10199 * gcc accepts anything that can be casted into void* without error */
10200 type_t *type = expression->base.type;
10202 if (type != type_error_type) {
10203 if (!is_type_pointer(type) && !is_type_integer(type)) {
10204 errorf(&expression->base.source_position,
10205 "cannot convert to a pointer type");
10206 } else if (warning.other && type != type_void_ptr) {
10207 warningf(&expression->base.source_position,
10208 "type of computed goto expression should be 'void*' not '%T'", type);
10210 expression = create_implicit_cast(expression, type_void_ptr);
10213 statement->gotos.expression = expression;
10215 if (token.type != T_IDENTIFIER) {
10217 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
10219 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
10220 eat_until_anchor();
10223 symbol_t *symbol = token.v.symbol;
10226 statement->gotos.label = get_label(symbol);
10229 /* remember the goto's in a list for later checking */
10230 *goto_anchor = &statement->gotos;
10231 goto_anchor = &statement->gotos.next;
10237 return create_invalid_statement();
10241 * Parse a continue statement.
10243 static statement_t *parse_continue(void)
10245 if (current_loop == NULL) {
10246 errorf(HERE, "continue statement not within loop");
10249 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10259 * Parse a break statement.
10261 static statement_t *parse_break(void)
10263 if (current_switch == NULL && current_loop == NULL) {
10264 errorf(HERE, "break statement not within loop or switch");
10267 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10277 * Parse a __leave statement.
10279 static statement_t *parse_leave_statement(void)
10281 if (current_try == NULL) {
10282 errorf(HERE, "__leave statement not within __try");
10285 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10295 * Check if a given entity represents a local variable.
10297 static bool is_local_variable(const entity_t *entity)
10299 if (entity->kind != ENTITY_VARIABLE)
10302 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10303 case STORAGE_CLASS_AUTO:
10304 case STORAGE_CLASS_REGISTER: {
10305 const type_t *type = skip_typeref(entity->declaration.type);
10306 if (is_type_function(type)) {
10318 * Check if a given expression represents a local variable.
10320 static bool expression_is_local_variable(const expression_t *expression)
10322 if (expression->base.kind != EXPR_REFERENCE) {
10325 const entity_t *entity = expression->reference.entity;
10326 return is_local_variable(entity);
10330 * Check if a given expression represents a local variable and
10331 * return its declaration then, else return NULL.
10333 entity_t *expression_is_variable(const expression_t *expression)
10335 if (expression->base.kind != EXPR_REFERENCE) {
10338 entity_t *entity = expression->reference.entity;
10339 if (entity->kind != ENTITY_VARIABLE)
10346 * Parse a return statement.
10348 static statement_t *parse_return(void)
10352 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10354 expression_t *return_value = NULL;
10355 if (token.type != ';') {
10356 return_value = parse_expression();
10357 mark_vars_read(return_value, NULL);
10360 const type_t *const func_type = skip_typeref(current_function->base.type);
10361 assert(is_type_function(func_type));
10362 type_t *const return_type = skip_typeref(func_type->function.return_type);
10364 if (return_value != NULL) {
10365 type_t *return_value_type = skip_typeref(return_value->base.type);
10367 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10368 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10369 if (warning.other) {
10370 warningf(&statement->base.source_position,
10371 "'return' with a value, in function returning void");
10373 return_value = NULL;
10375 assign_error_t error = semantic_assign(return_type, return_value);
10376 report_assign_error(error, return_type, return_value, "'return'",
10377 &statement->base.source_position);
10378 return_value = create_implicit_cast(return_value, return_type);
10380 /* check for returning address of a local var */
10381 if (warning.other && return_value != NULL
10382 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10383 const expression_t *expression = return_value->unary.value;
10384 if (expression_is_local_variable(expression)) {
10385 warningf(&statement->base.source_position,
10386 "function returns address of local variable");
10389 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10390 warningf(&statement->base.source_position,
10391 "'return' without value, in function returning non-void");
10393 statement->returns.value = return_value;
10402 * Parse a declaration statement.
10404 static statement_t *parse_declaration_statement(void)
10406 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10408 entity_t *before = current_scope->last_entity;
10410 parse_external_declaration();
10412 parse_declaration(record_entity, DECL_FLAGS_NONE);
10415 if (before == NULL) {
10416 statement->declaration.declarations_begin = current_scope->entities;
10418 statement->declaration.declarations_begin = before->base.next;
10420 statement->declaration.declarations_end = current_scope->last_entity;
10426 * Parse an expression statement, ie. expr ';'.
10428 static statement_t *parse_expression_statement(void)
10430 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10432 expression_t *const expr = parse_expression();
10433 statement->expression.expression = expr;
10434 mark_vars_read(expr, ENT_ANY);
10443 * Parse a microsoft __try { } __finally { } or
10444 * __try{ } __except() { }
10446 static statement_t *parse_ms_try_statment(void)
10448 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10451 PUSH_PARENT(statement);
10453 ms_try_statement_t *rem = current_try;
10454 current_try = &statement->ms_try;
10455 statement->ms_try.try_statement = parse_compound_statement(false);
10460 if (token.type == T___except) {
10463 add_anchor_token(')');
10464 expression_t *const expr = parse_expression();
10465 mark_vars_read(expr, NULL);
10466 type_t * type = skip_typeref(expr->base.type);
10467 if (is_type_integer(type)) {
10468 type = promote_integer(type);
10469 } else if (is_type_valid(type)) {
10470 errorf(&expr->base.source_position,
10471 "__expect expression is not an integer, but '%T'", type);
10472 type = type_error_type;
10474 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10475 rem_anchor_token(')');
10477 statement->ms_try.final_statement = parse_compound_statement(false);
10478 } else if (token.type == T__finally) {
10480 statement->ms_try.final_statement = parse_compound_statement(false);
10482 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10483 return create_invalid_statement();
10487 return create_invalid_statement();
10490 static statement_t *parse_empty_statement(void)
10492 if (warning.empty_statement) {
10493 warningf(HERE, "statement is empty");
10495 statement_t *const statement = create_empty_statement();
10500 static statement_t *parse_local_label_declaration(void)
10502 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10506 entity_t *begin = NULL, *end = NULL;
10509 if (token.type != T_IDENTIFIER) {
10510 parse_error_expected("while parsing local label declaration",
10511 T_IDENTIFIER, NULL);
10514 symbol_t *symbol = token.v.symbol;
10515 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10516 if (entity != NULL && entity->base.parent_scope == current_scope) {
10517 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10518 symbol, &entity->base.source_position);
10520 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10522 entity->base.parent_scope = current_scope;
10523 entity->base.namespc = NAMESPACE_LABEL;
10524 entity->base.source_position = token.source_position;
10525 entity->base.symbol = symbol;
10528 end->base.next = entity;
10533 environment_push(entity);
10537 if (token.type != ',')
10543 statement->declaration.declarations_begin = begin;
10544 statement->declaration.declarations_end = end;
10548 static void parse_namespace_definition(void)
10552 entity_t *entity = NULL;
10553 symbol_t *symbol = NULL;
10555 if (token.type == T_IDENTIFIER) {
10556 symbol = token.v.symbol;
10559 entity = get_entity(symbol, NAMESPACE_NORMAL);
10560 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10561 && entity->base.parent_scope == current_scope) {
10562 error_redefined_as_different_kind(&token.source_position,
10563 entity, ENTITY_NAMESPACE);
10568 if (entity == NULL) {
10569 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10570 entity->base.symbol = symbol;
10571 entity->base.source_position = token.source_position;
10572 entity->base.namespc = NAMESPACE_NORMAL;
10573 entity->base.parent_scope = current_scope;
10576 if (token.type == '=') {
10577 /* TODO: parse namespace alias */
10578 panic("namespace alias definition not supported yet");
10581 environment_push(entity);
10582 append_entity(current_scope, entity);
10584 size_t const top = environment_top();
10585 scope_t *old_scope = scope_push(&entity->namespacee.members);
10592 assert(current_scope == &entity->namespacee.members);
10593 scope_pop(old_scope);
10594 environment_pop_to(top);
10598 * Parse a statement.
10599 * There's also parse_statement() which additionally checks for
10600 * "statement has no effect" warnings
10602 static statement_t *intern_parse_statement(void)
10604 statement_t *statement = NULL;
10606 /* declaration or statement */
10607 add_anchor_token(';');
10608 switch (token.type) {
10609 case T_IDENTIFIER: {
10610 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10611 if (la1_type == ':') {
10612 statement = parse_label_statement();
10613 } else if (is_typedef_symbol(token.v.symbol)) {
10614 statement = parse_declaration_statement();
10616 /* it's an identifier, the grammar says this must be an
10617 * expression statement. However it is common that users mistype
10618 * declaration types, so we guess a bit here to improve robustness
10619 * for incorrect programs */
10620 switch (la1_type) {
10623 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10624 goto expression_statment;
10629 statement = parse_declaration_statement();
10633 expression_statment:
10634 statement = parse_expression_statement();
10641 case T___extension__:
10642 /* This can be a prefix to a declaration or an expression statement.
10643 * We simply eat it now and parse the rest with tail recursion. */
10646 } while (token.type == T___extension__);
10647 bool old_gcc_extension = in_gcc_extension;
10648 in_gcc_extension = true;
10649 statement = intern_parse_statement();
10650 in_gcc_extension = old_gcc_extension;
10654 statement = parse_declaration_statement();
10658 statement = parse_local_label_declaration();
10661 case ';': statement = parse_empty_statement(); break;
10662 case '{': statement = parse_compound_statement(false); break;
10663 case T___leave: statement = parse_leave_statement(); break;
10664 case T___try: statement = parse_ms_try_statment(); break;
10665 case T_asm: statement = parse_asm_statement(); break;
10666 case T_break: statement = parse_break(); break;
10667 case T_case: statement = parse_case_statement(); break;
10668 case T_continue: statement = parse_continue(); break;
10669 case T_default: statement = parse_default_statement(); break;
10670 case T_do: statement = parse_do(); break;
10671 case T_for: statement = parse_for(); break;
10672 case T_goto: statement = parse_goto(); break;
10673 case T_if: statement = parse_if(); break;
10674 case T_return: statement = parse_return(); break;
10675 case T_switch: statement = parse_switch(); break;
10676 case T_while: statement = parse_while(); break;
10679 statement = parse_expression_statement();
10683 errorf(HERE, "unexpected token %K while parsing statement", &token);
10684 statement = create_invalid_statement();
10689 rem_anchor_token(';');
10691 assert(statement != NULL
10692 && statement->base.source_position.input_name != NULL);
10698 * parse a statement and emits "statement has no effect" warning if needed
10699 * (This is really a wrapper around intern_parse_statement with check for 1
10700 * single warning. It is needed, because for statement expressions we have
10701 * to avoid the warning on the last statement)
10703 static statement_t *parse_statement(void)
10705 statement_t *statement = intern_parse_statement();
10707 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10708 expression_t *expression = statement->expression.expression;
10709 if (!expression_has_effect(expression)) {
10710 warningf(&expression->base.source_position,
10711 "statement has no effect");
10719 * Parse a compound statement.
10721 static statement_t *parse_compound_statement(bool inside_expression_statement)
10723 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10725 PUSH_PARENT(statement);
10728 add_anchor_token('}');
10729 /* tokens, which can start a statement */
10730 /* TODO MS, __builtin_FOO */
10731 add_anchor_token('!');
10732 add_anchor_token('&');
10733 add_anchor_token('(');
10734 add_anchor_token('*');
10735 add_anchor_token('+');
10736 add_anchor_token('-');
10737 add_anchor_token('{');
10738 add_anchor_token('~');
10739 add_anchor_token(T_CHARACTER_CONSTANT);
10740 add_anchor_token(T_COLONCOLON);
10741 add_anchor_token(T_FLOATINGPOINT);
10742 add_anchor_token(T_IDENTIFIER);
10743 add_anchor_token(T_INTEGER);
10744 add_anchor_token(T_MINUSMINUS);
10745 add_anchor_token(T_PLUSPLUS);
10746 add_anchor_token(T_STRING_LITERAL);
10747 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10748 add_anchor_token(T_WIDE_STRING_LITERAL);
10749 add_anchor_token(T__Bool);
10750 add_anchor_token(T__Complex);
10751 add_anchor_token(T__Imaginary);
10752 add_anchor_token(T___FUNCTION__);
10753 add_anchor_token(T___PRETTY_FUNCTION__);
10754 add_anchor_token(T___alignof__);
10755 add_anchor_token(T___attribute__);
10756 add_anchor_token(T___builtin_va_start);
10757 add_anchor_token(T___extension__);
10758 add_anchor_token(T___func__);
10759 add_anchor_token(T___imag__);
10760 add_anchor_token(T___label__);
10761 add_anchor_token(T___real__);
10762 add_anchor_token(T___thread);
10763 add_anchor_token(T_asm);
10764 add_anchor_token(T_auto);
10765 add_anchor_token(T_bool);
10766 add_anchor_token(T_break);
10767 add_anchor_token(T_case);
10768 add_anchor_token(T_char);
10769 add_anchor_token(T_class);
10770 add_anchor_token(T_const);
10771 add_anchor_token(T_const_cast);
10772 add_anchor_token(T_continue);
10773 add_anchor_token(T_default);
10774 add_anchor_token(T_delete);
10775 add_anchor_token(T_double);
10776 add_anchor_token(T_do);
10777 add_anchor_token(T_dynamic_cast);
10778 add_anchor_token(T_enum);
10779 add_anchor_token(T_extern);
10780 add_anchor_token(T_false);
10781 add_anchor_token(T_float);
10782 add_anchor_token(T_for);
10783 add_anchor_token(T_goto);
10784 add_anchor_token(T_if);
10785 add_anchor_token(T_inline);
10786 add_anchor_token(T_int);
10787 add_anchor_token(T_long);
10788 add_anchor_token(T_new);
10789 add_anchor_token(T_operator);
10790 add_anchor_token(T_register);
10791 add_anchor_token(T_reinterpret_cast);
10792 add_anchor_token(T_restrict);
10793 add_anchor_token(T_return);
10794 add_anchor_token(T_short);
10795 add_anchor_token(T_signed);
10796 add_anchor_token(T_sizeof);
10797 add_anchor_token(T_static);
10798 add_anchor_token(T_static_cast);
10799 add_anchor_token(T_struct);
10800 add_anchor_token(T_switch);
10801 add_anchor_token(T_template);
10802 add_anchor_token(T_this);
10803 add_anchor_token(T_throw);
10804 add_anchor_token(T_true);
10805 add_anchor_token(T_try);
10806 add_anchor_token(T_typedef);
10807 add_anchor_token(T_typeid);
10808 add_anchor_token(T_typename);
10809 add_anchor_token(T_typeof);
10810 add_anchor_token(T_union);
10811 add_anchor_token(T_unsigned);
10812 add_anchor_token(T_using);
10813 add_anchor_token(T_void);
10814 add_anchor_token(T_volatile);
10815 add_anchor_token(T_wchar_t);
10816 add_anchor_token(T_while);
10818 size_t const top = environment_top();
10819 scope_t *old_scope = scope_push(&statement->compound.scope);
10821 statement_t **anchor = &statement->compound.statements;
10822 bool only_decls_so_far = true;
10823 while (token.type != '}') {
10824 if (token.type == T_EOF) {
10825 errorf(&statement->base.source_position,
10826 "EOF while parsing compound statement");
10829 statement_t *sub_statement = intern_parse_statement();
10830 if (is_invalid_statement(sub_statement)) {
10831 /* an error occurred. if we are at an anchor, return */
10837 if (warning.declaration_after_statement) {
10838 if (sub_statement->kind != STATEMENT_DECLARATION) {
10839 only_decls_so_far = false;
10840 } else if (!only_decls_so_far) {
10841 warningf(&sub_statement->base.source_position,
10842 "ISO C90 forbids mixed declarations and code");
10846 *anchor = sub_statement;
10848 while (sub_statement->base.next != NULL)
10849 sub_statement = sub_statement->base.next;
10851 anchor = &sub_statement->base.next;
10855 /* look over all statements again to produce no effect warnings */
10856 if (warning.unused_value) {
10857 statement_t *sub_statement = statement->compound.statements;
10858 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10859 if (sub_statement->kind != STATEMENT_EXPRESSION)
10861 /* don't emit a warning for the last expression in an expression
10862 * statement as it has always an effect */
10863 if (inside_expression_statement && sub_statement->base.next == NULL)
10866 expression_t *expression = sub_statement->expression.expression;
10867 if (!expression_has_effect(expression)) {
10868 warningf(&expression->base.source_position,
10869 "statement has no effect");
10875 rem_anchor_token(T_while);
10876 rem_anchor_token(T_wchar_t);
10877 rem_anchor_token(T_volatile);
10878 rem_anchor_token(T_void);
10879 rem_anchor_token(T_using);
10880 rem_anchor_token(T_unsigned);
10881 rem_anchor_token(T_union);
10882 rem_anchor_token(T_typeof);
10883 rem_anchor_token(T_typename);
10884 rem_anchor_token(T_typeid);
10885 rem_anchor_token(T_typedef);
10886 rem_anchor_token(T_try);
10887 rem_anchor_token(T_true);
10888 rem_anchor_token(T_throw);
10889 rem_anchor_token(T_this);
10890 rem_anchor_token(T_template);
10891 rem_anchor_token(T_switch);
10892 rem_anchor_token(T_struct);
10893 rem_anchor_token(T_static_cast);
10894 rem_anchor_token(T_static);
10895 rem_anchor_token(T_sizeof);
10896 rem_anchor_token(T_signed);
10897 rem_anchor_token(T_short);
10898 rem_anchor_token(T_return);
10899 rem_anchor_token(T_restrict);
10900 rem_anchor_token(T_reinterpret_cast);
10901 rem_anchor_token(T_register);
10902 rem_anchor_token(T_operator);
10903 rem_anchor_token(T_new);
10904 rem_anchor_token(T_long);
10905 rem_anchor_token(T_int);
10906 rem_anchor_token(T_inline);
10907 rem_anchor_token(T_if);
10908 rem_anchor_token(T_goto);
10909 rem_anchor_token(T_for);
10910 rem_anchor_token(T_float);
10911 rem_anchor_token(T_false);
10912 rem_anchor_token(T_extern);
10913 rem_anchor_token(T_enum);
10914 rem_anchor_token(T_dynamic_cast);
10915 rem_anchor_token(T_do);
10916 rem_anchor_token(T_double);
10917 rem_anchor_token(T_delete);
10918 rem_anchor_token(T_default);
10919 rem_anchor_token(T_continue);
10920 rem_anchor_token(T_const_cast);
10921 rem_anchor_token(T_const);
10922 rem_anchor_token(T_class);
10923 rem_anchor_token(T_char);
10924 rem_anchor_token(T_case);
10925 rem_anchor_token(T_break);
10926 rem_anchor_token(T_bool);
10927 rem_anchor_token(T_auto);
10928 rem_anchor_token(T_asm);
10929 rem_anchor_token(T___thread);
10930 rem_anchor_token(T___real__);
10931 rem_anchor_token(T___label__);
10932 rem_anchor_token(T___imag__);
10933 rem_anchor_token(T___func__);
10934 rem_anchor_token(T___extension__);
10935 rem_anchor_token(T___builtin_va_start);
10936 rem_anchor_token(T___attribute__);
10937 rem_anchor_token(T___alignof__);
10938 rem_anchor_token(T___PRETTY_FUNCTION__);
10939 rem_anchor_token(T___FUNCTION__);
10940 rem_anchor_token(T__Imaginary);
10941 rem_anchor_token(T__Complex);
10942 rem_anchor_token(T__Bool);
10943 rem_anchor_token(T_WIDE_STRING_LITERAL);
10944 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10945 rem_anchor_token(T_STRING_LITERAL);
10946 rem_anchor_token(T_PLUSPLUS);
10947 rem_anchor_token(T_MINUSMINUS);
10948 rem_anchor_token(T_INTEGER);
10949 rem_anchor_token(T_IDENTIFIER);
10950 rem_anchor_token(T_FLOATINGPOINT);
10951 rem_anchor_token(T_COLONCOLON);
10952 rem_anchor_token(T_CHARACTER_CONSTANT);
10953 rem_anchor_token('~');
10954 rem_anchor_token('{');
10955 rem_anchor_token('-');
10956 rem_anchor_token('+');
10957 rem_anchor_token('*');
10958 rem_anchor_token('(');
10959 rem_anchor_token('&');
10960 rem_anchor_token('!');
10961 rem_anchor_token('}');
10962 assert(current_scope == &statement->compound.scope);
10963 scope_pop(old_scope);
10964 environment_pop_to(top);
10971 * Check for unused global static functions and variables
10973 static void check_unused_globals(void)
10975 if (!warning.unused_function && !warning.unused_variable)
10978 for (const entity_t *entity = file_scope->entities; entity != NULL;
10979 entity = entity->base.next) {
10980 if (!is_declaration(entity))
10983 const declaration_t *declaration = &entity->declaration;
10984 if (declaration->used ||
10985 declaration->modifiers & DM_UNUSED ||
10986 declaration->modifiers & DM_USED ||
10987 declaration->storage_class != STORAGE_CLASS_STATIC)
10990 type_t *const type = declaration->type;
10992 if (entity->kind == ENTITY_FUNCTION) {
10993 /* inhibit warning for static inline functions */
10994 if (entity->function.is_inline)
10997 s = entity->function.statement != NULL ? "defined" : "declared";
11002 warningf(&declaration->base.source_position, "'%#T' %s but not used",
11003 type, declaration->base.symbol, s);
11007 static void parse_global_asm(void)
11009 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
11014 statement->asms.asm_text = parse_string_literals();
11015 statement->base.next = unit->global_asm;
11016 unit->global_asm = statement;
11024 static void parse_linkage_specification(void)
11027 assert(token.type == T_STRING_LITERAL);
11029 const char *linkage = parse_string_literals().begin;
11031 linkage_kind_t old_linkage = current_linkage;
11032 linkage_kind_t new_linkage;
11033 if (strcmp(linkage, "C") == 0) {
11034 new_linkage = LINKAGE_C;
11035 } else if (strcmp(linkage, "C++") == 0) {
11036 new_linkage = LINKAGE_CXX;
11038 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
11039 new_linkage = LINKAGE_INVALID;
11041 current_linkage = new_linkage;
11043 if (token.type == '{') {
11052 assert(current_linkage == new_linkage);
11053 current_linkage = old_linkage;
11056 static void parse_external(void)
11058 switch (token.type) {
11059 DECLARATION_START_NO_EXTERN
11061 case T___extension__:
11062 /* tokens below are for implicit int */
11063 case '&': /* & x; -> int& x; (and error later, because C++ has no
11065 case '*': /* * x; -> int* x; */
11066 case '(': /* (x); -> int (x); */
11067 parse_external_declaration();
11071 if (look_ahead(1)->type == T_STRING_LITERAL) {
11072 parse_linkage_specification();
11074 parse_external_declaration();
11079 parse_global_asm();
11083 parse_namespace_definition();
11087 if (!strict_mode) {
11089 warningf(HERE, "stray ';' outside of function");
11096 errorf(HERE, "stray %K outside of function", &token);
11097 if (token.type == '(' || token.type == '{' || token.type == '[')
11098 eat_until_matching_token(token.type);
11104 static void parse_externals(void)
11106 add_anchor_token('}');
11107 add_anchor_token(T_EOF);
11110 unsigned char token_anchor_copy[T_LAST_TOKEN];
11111 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
11114 while (token.type != T_EOF && token.type != '}') {
11116 bool anchor_leak = false;
11117 for (int i = 0; i != T_LAST_TOKEN; ++i) {
11118 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
11120 errorf(HERE, "Leaked anchor token %k %d times", i, count);
11121 anchor_leak = true;
11124 if (in_gcc_extension) {
11125 errorf(HERE, "Leaked __extension__");
11126 anchor_leak = true;
11136 rem_anchor_token(T_EOF);
11137 rem_anchor_token('}');
11141 * Parse a translation unit.
11143 static void parse_translation_unit(void)
11145 add_anchor_token(T_EOF);
11150 if (token.type == T_EOF)
11153 errorf(HERE, "stray %K outside of function", &token);
11154 if (token.type == '(' || token.type == '{' || token.type == '[')
11155 eat_until_matching_token(token.type);
11163 * @return the translation unit or NULL if errors occurred.
11165 void start_parsing(void)
11167 environment_stack = NEW_ARR_F(stack_entry_t, 0);
11168 label_stack = NEW_ARR_F(stack_entry_t, 0);
11169 diagnostic_count = 0;
11173 type_set_output(stderr);
11174 ast_set_output(stderr);
11176 assert(unit == NULL);
11177 unit = allocate_ast_zero(sizeof(unit[0]));
11179 assert(file_scope == NULL);
11180 file_scope = &unit->scope;
11182 assert(current_scope == NULL);
11183 scope_push(&unit->scope);
11186 translation_unit_t *finish_parsing(void)
11188 assert(current_scope == &unit->scope);
11191 assert(file_scope == &unit->scope);
11192 check_unused_globals();
11195 DEL_ARR_F(environment_stack);
11196 DEL_ARR_F(label_stack);
11198 translation_unit_t *result = unit;
11203 /* GCC allows global arrays without size and assigns them a length of one,
11204 * if no different declaration follows */
11205 static void complete_incomplete_arrays(void)
11207 size_t n = ARR_LEN(incomplete_arrays);
11208 for (size_t i = 0; i != n; ++i) {
11209 declaration_t *const decl = incomplete_arrays[i];
11210 type_t *const orig_type = decl->type;
11211 type_t *const type = skip_typeref(orig_type);
11213 if (!is_type_incomplete(type))
11216 if (warning.other) {
11217 warningf(&decl->base.source_position,
11218 "array '%#T' assumed to have one element",
11219 orig_type, decl->base.symbol);
11222 type_t *const new_type = duplicate_type(type);
11223 new_type->array.size_constant = true;
11224 new_type->array.has_implicit_size = true;
11225 new_type->array.size = 1;
11227 type_t *const result = typehash_insert(new_type);
11228 if (type != result)
11231 decl->type = result;
11237 lookahead_bufpos = 0;
11238 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11241 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11242 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11243 parse_translation_unit();
11244 complete_incomplete_arrays();
11245 DEL_ARR_F(incomplete_arrays);
11246 incomplete_arrays = NULL;
11250 * Initialize the parser.
11252 void init_parser(void)
11254 sym_anonymous = symbol_table_insert("<anonymous>");
11256 if (c_mode & _MS) {
11257 /* add predefined symbols for extended-decl-modifier */
11258 sym_align = symbol_table_insert("align");
11259 sym_allocate = symbol_table_insert("allocate");
11260 sym_dllimport = symbol_table_insert("dllimport");
11261 sym_dllexport = symbol_table_insert("dllexport");
11262 sym_naked = symbol_table_insert("naked");
11263 sym_noinline = symbol_table_insert("noinline");
11264 sym_noreturn = symbol_table_insert("noreturn");
11265 sym_nothrow = symbol_table_insert("nothrow");
11266 sym_novtable = symbol_table_insert("novtable");
11267 sym_property = symbol_table_insert("property");
11268 sym_get = symbol_table_insert("get");
11269 sym_put = symbol_table_insert("put");
11270 sym_selectany = symbol_table_insert("selectany");
11271 sym_thread = symbol_table_insert("thread");
11272 sym_uuid = symbol_table_insert("uuid");
11273 sym_deprecated = symbol_table_insert("deprecated");
11274 sym_restrict = symbol_table_insert("restrict");
11275 sym_noalias = symbol_table_insert("noalias");
11277 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11279 init_expression_parsers();
11280 obstack_init(&temp_obst);
11282 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11283 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11287 * Terminate the parser.
11289 void exit_parser(void)
11291 obstack_free(&temp_obst, NULL);