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. */
81 decl_modifiers_t modifiers; /**< declaration modifiers */
82 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
83 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
84 symbol_t *get_property_sym; /**< the name of the get property if set. */
85 symbol_t *put_property_sym; /**< the name of the put property if set. */
90 * An environment for parsing initializers (and compound literals).
92 typedef struct parse_initializer_env_t {
93 type_t *type; /**< the type of the initializer. In case of an
94 array type with unspecified size this gets
95 adjusted to the actual size. */
96 entity_t *entity; /**< the variable that is initialized if any */
97 bool must_be_constant;
98 } parse_initializer_env_t;
101 * Capture a MS __base extension.
103 typedef struct based_spec_t {
104 source_position_t source_position;
105 variable_t *base_variable;
108 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
110 /** The current token. */
111 static token_t token;
112 /** The lookahead ring-buffer. */
113 static token_t lookahead_buffer[MAX_LOOKAHEAD];
114 /** Position of the next token in the lookahead buffer. */
115 static int lookahead_bufpos;
116 static stack_entry_t *environment_stack = NULL;
117 static stack_entry_t *label_stack = NULL;
118 static scope_t *file_scope = NULL;
119 static scope_t *current_scope = NULL;
120 /** Point to the current function declaration if inside a function. */
121 static function_t *current_function = NULL;
122 static entity_t *current_init_decl = NULL;
123 static switch_statement_t *current_switch = NULL;
124 static statement_t *current_loop = NULL;
125 static statement_t *current_parent = NULL;
126 static ms_try_statement_t *current_try = NULL;
127 static linkage_kind_t current_linkage = LINKAGE_INVALID;
128 static goto_statement_t *goto_first = NULL;
129 static goto_statement_t **goto_anchor = NULL;
130 static label_statement_t *label_first = NULL;
131 static label_statement_t **label_anchor = NULL;
132 /** current translation unit. */
133 static translation_unit_t *unit = NULL;
134 /** true if we are in a type property context (evaluation only for type. */
135 static bool in_type_prop = false;
136 /** true in we are in a __extension__ context. */
137 static bool in_gcc_extension = false;
138 static struct obstack temp_obst;
139 static entity_t *anonymous_entity;
142 #define PUSH_PARENT(stmt) \
143 statement_t *const prev_parent = current_parent; \
144 ((void)(current_parent = (stmt)))
145 #define POP_PARENT ((void)(current_parent = prev_parent))
147 /** special symbol used for anonymous entities. */
148 static const symbol_t *sym_anonymous = NULL;
150 /* symbols for Microsoft extended-decl-modifier */
151 static const symbol_t *sym_align = NULL;
152 static const symbol_t *sym_allocate = NULL;
153 static const symbol_t *sym_dllimport = NULL;
154 static const symbol_t *sym_dllexport = NULL;
155 static const symbol_t *sym_naked = NULL;
156 static const symbol_t *sym_noinline = NULL;
157 static const symbol_t *sym_noreturn = NULL;
158 static const symbol_t *sym_nothrow = NULL;
159 static const symbol_t *sym_novtable = NULL;
160 static const symbol_t *sym_property = NULL;
161 static const symbol_t *sym_get = NULL;
162 static const symbol_t *sym_put = NULL;
163 static const symbol_t *sym_selectany = NULL;
164 static const symbol_t *sym_thread = NULL;
165 static const symbol_t *sym_uuid = NULL;
166 static const symbol_t *sym_deprecated = NULL;
167 static const symbol_t *sym_restrict = NULL;
168 static const symbol_t *sym_noalias = NULL;
170 /** The token anchor set */
171 static unsigned char token_anchor_set[T_LAST_TOKEN];
173 /** The current source position. */
174 #define HERE (&token.source_position)
176 /** true if we are in GCC mode. */
177 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
179 static type_t *type_valist;
181 static statement_t *parse_compound_statement(bool inside_expression_statement);
182 static statement_t *parse_statement(void);
184 static expression_t *parse_sub_expression(precedence_t);
185 static expression_t *parse_expression(void);
186 static type_t *parse_typename(void);
187 static void parse_externals(void);
188 static void parse_external(void);
190 static void parse_compound_type_entries(compound_t *compound_declaration);
191 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
192 bool may_be_abstract,
193 bool create_compound_member);
194 static entity_t *record_entity(entity_t *entity, bool is_definition);
196 static void semantic_comparison(binary_expression_t *expression);
198 #define STORAGE_CLASSES \
206 #define STORAGE_CLASSES_NO_EXTERN \
213 #define TYPE_QUALIFIERS \
218 case T__forceinline: \
219 case T___attribute__:
221 #define COMPLEX_SPECIFIERS \
223 #define IMAGINARY_SPECIFIERS \
226 #define TYPE_SPECIFIERS \
228 case T___builtin_va_list: \
247 #define DECLARATION_START \
252 #define DECLARATION_START_NO_EXTERN \
253 STORAGE_CLASSES_NO_EXTERN \
257 #define TYPENAME_START \
261 #define EXPRESSION_START \
270 case T_CHARACTER_CONSTANT: \
271 case T_FLOATINGPOINT: \
275 case T_STRING_LITERAL: \
276 case T_WIDE_CHARACTER_CONSTANT: \
277 case T_WIDE_STRING_LITERAL: \
278 case T___FUNCDNAME__: \
279 case T___FUNCSIG__: \
280 case T___FUNCTION__: \
281 case T___PRETTY_FUNCTION__: \
282 case T___alignof__: \
283 case T___builtin_alloca: \
284 case T___builtin_classify_type: \
285 case T___builtin_constant_p: \
286 case T___builtin_expect: \
287 case T___builtin_huge_val: \
288 case T___builtin_inf: \
289 case T___builtin_inff: \
290 case T___builtin_infl: \
291 case T___builtin_isgreater: \
292 case T___builtin_isgreaterequal: \
293 case T___builtin_isless: \
294 case T___builtin_islessequal: \
295 case T___builtin_islessgreater: \
296 case T___builtin_isunordered: \
297 case T___builtin_nan: \
298 case T___builtin_nanf: \
299 case T___builtin_nanl: \
300 case T___builtin_offsetof: \
301 case T___builtin_prefetch: \
302 case T___builtin_va_arg: \
303 case T___builtin_va_end: \
304 case T___builtin_va_start: \
315 * Allocate an AST node with given size and
316 * initialize all fields with zero.
318 static void *allocate_ast_zero(size_t size)
320 void *res = allocate_ast(size);
321 memset(res, 0, size);
325 static size_t get_entity_struct_size(entity_kind_t kind)
327 static const size_t sizes[] = {
328 [ENTITY_VARIABLE] = sizeof(variable_t),
329 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
330 [ENTITY_FUNCTION] = sizeof(function_t),
331 [ENTITY_TYPEDEF] = sizeof(typedef_t),
332 [ENTITY_STRUCT] = sizeof(compound_t),
333 [ENTITY_UNION] = sizeof(compound_t),
334 [ENTITY_ENUM] = sizeof(enum_t),
335 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
336 [ENTITY_LABEL] = sizeof(label_t),
337 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
338 [ENTITY_NAMESPACE] = sizeof(namespace_t)
340 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
341 assert(sizes[kind] != 0);
345 static entity_t *allocate_entity_zero(entity_kind_t kind)
347 size_t size = get_entity_struct_size(kind);
348 entity_t *entity = allocate_ast_zero(size);
354 * Returns the size of a statement node.
356 * @param kind the statement kind
358 static size_t get_statement_struct_size(statement_kind_t kind)
360 static const size_t sizes[] = {
361 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
362 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
363 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
364 [STATEMENT_RETURN] = sizeof(return_statement_t),
365 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
366 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
367 [STATEMENT_IF] = sizeof(if_statement_t),
368 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
369 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
370 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
371 [STATEMENT_BREAK] = sizeof(statement_base_t),
372 [STATEMENT_GOTO] = sizeof(goto_statement_t),
373 [STATEMENT_LABEL] = sizeof(label_statement_t),
374 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
375 [STATEMENT_WHILE] = sizeof(while_statement_t),
376 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
377 [STATEMENT_FOR] = sizeof(for_statement_t),
378 [STATEMENT_ASM] = sizeof(asm_statement_t),
379 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
380 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
382 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
383 assert(sizes[kind] != 0);
388 * Returns the size of an expression node.
390 * @param kind the expression kind
392 static size_t get_expression_struct_size(expression_kind_t kind)
394 static const size_t sizes[] = {
395 [EXPR_INVALID] = sizeof(expression_base_t),
396 [EXPR_REFERENCE] = sizeof(reference_expression_t),
397 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
398 [EXPR_CONST] = sizeof(const_expression_t),
399 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
400 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
401 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
402 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
403 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
404 [EXPR_CALL] = sizeof(call_expression_t),
405 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
406 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
407 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
408 [EXPR_SELECT] = sizeof(select_expression_t),
409 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
410 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
411 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
412 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
413 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
414 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
415 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
416 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
417 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
418 [EXPR_VA_START] = sizeof(va_start_expression_t),
419 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
420 [EXPR_STATEMENT] = sizeof(statement_expression_t),
421 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
423 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
424 return sizes[EXPR_UNARY_FIRST];
426 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
427 return sizes[EXPR_BINARY_FIRST];
429 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
430 assert(sizes[kind] != 0);
435 * Allocate a statement node of given kind and initialize all
438 static statement_t *allocate_statement_zero(statement_kind_t kind)
440 size_t size = get_statement_struct_size(kind);
441 statement_t *res = allocate_ast_zero(size);
443 res->base.kind = kind;
444 res->base.parent = current_parent;
445 res->base.source_position = token.source_position;
450 * Allocate an expression node of given kind and initialize all
453 static expression_t *allocate_expression_zero(expression_kind_t kind)
455 size_t size = get_expression_struct_size(kind);
456 expression_t *res = allocate_ast_zero(size);
458 res->base.kind = kind;
459 res->base.type = type_error_type;
460 res->base.source_position = token.source_position;
465 * Creates a new invalid expression.
467 static expression_t *create_invalid_expression(void)
469 return allocate_expression_zero(EXPR_INVALID);
473 * Creates a new invalid statement.
475 static statement_t *create_invalid_statement(void)
477 return allocate_statement_zero(STATEMENT_INVALID);
481 * Allocate a new empty statement.
483 static statement_t *create_empty_statement(void)
485 return allocate_statement_zero(STATEMENT_EMPTY);
489 * Returns the size of a type node.
491 * @param kind the type kind
493 static size_t get_type_struct_size(type_kind_t kind)
495 static const size_t sizes[] = {
496 [TYPE_ATOMIC] = sizeof(atomic_type_t),
497 [TYPE_COMPLEX] = sizeof(complex_type_t),
498 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
499 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
500 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
501 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
502 [TYPE_ENUM] = sizeof(enum_type_t),
503 [TYPE_FUNCTION] = sizeof(function_type_t),
504 [TYPE_POINTER] = sizeof(pointer_type_t),
505 [TYPE_ARRAY] = sizeof(array_type_t),
506 [TYPE_BUILTIN] = sizeof(builtin_type_t),
507 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
508 [TYPE_TYPEOF] = sizeof(typeof_type_t),
510 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
511 assert(kind <= TYPE_TYPEOF);
512 assert(sizes[kind] != 0);
517 * Allocate a type node of given kind and initialize all
520 * @param kind type kind to allocate
522 static type_t *allocate_type_zero(type_kind_t kind)
524 size_t size = get_type_struct_size(kind);
525 type_t *res = obstack_alloc(type_obst, size);
526 memset(res, 0, size);
527 res->base.kind = kind;
533 * Returns the size of an initializer node.
535 * @param kind the initializer kind
537 static size_t get_initializer_size(initializer_kind_t kind)
539 static const size_t sizes[] = {
540 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
541 [INITIALIZER_STRING] = sizeof(initializer_string_t),
542 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
543 [INITIALIZER_LIST] = sizeof(initializer_list_t),
544 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
546 assert(kind < sizeof(sizes) / sizeof(*sizes));
547 assert(sizes[kind] != 0);
552 * Allocate an initializer node of given kind and initialize all
555 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
557 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
564 * Free a type from the type obstack.
566 static void free_type(void *type)
568 obstack_free(type_obst, type);
572 * Returns the index of the top element of the environment stack.
574 static size_t environment_top(void)
576 return ARR_LEN(environment_stack);
580 * Returns the index of the top element of the global label stack.
582 static size_t label_top(void)
584 return ARR_LEN(label_stack);
588 * Return the next token.
590 static inline void next_token(void)
592 token = lookahead_buffer[lookahead_bufpos];
593 lookahead_buffer[lookahead_bufpos] = lexer_token;
596 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
599 print_token(stderr, &token);
600 fprintf(stderr, "\n");
605 * Return the next token with a given lookahead.
607 static inline const token_t *look_ahead(int num)
609 assert(num > 0 && num <= MAX_LOOKAHEAD);
610 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
611 return &lookahead_buffer[pos];
615 * Adds a token to the token anchor set (a multi-set).
617 static void add_anchor_token(int token_type)
619 assert(0 <= token_type && token_type < T_LAST_TOKEN);
620 ++token_anchor_set[token_type];
623 static int save_and_reset_anchor_state(int token_type)
625 assert(0 <= token_type && token_type < T_LAST_TOKEN);
626 int count = token_anchor_set[token_type];
627 token_anchor_set[token_type] = 0;
631 static void restore_anchor_state(int token_type, int count)
633 assert(0 <= token_type && token_type < T_LAST_TOKEN);
634 token_anchor_set[token_type] = count;
638 * Remove a token from the token anchor set (a multi-set).
640 static void rem_anchor_token(int token_type)
642 assert(0 <= token_type && token_type < T_LAST_TOKEN);
643 assert(token_anchor_set[token_type] != 0);
644 --token_anchor_set[token_type];
647 static bool at_anchor(void)
651 return token_anchor_set[token.type];
655 * Eat tokens until a matching token is found.
657 static void eat_until_matching_token(int type)
661 case '(': end_token = ')'; break;
662 case '{': end_token = '}'; break;
663 case '[': end_token = ']'; break;
664 default: end_token = type; break;
667 unsigned parenthesis_count = 0;
668 unsigned brace_count = 0;
669 unsigned bracket_count = 0;
670 while (token.type != end_token ||
671 parenthesis_count != 0 ||
673 bracket_count != 0) {
674 switch (token.type) {
676 case '(': ++parenthesis_count; break;
677 case '{': ++brace_count; break;
678 case '[': ++bracket_count; break;
681 if (parenthesis_count > 0)
691 if (bracket_count > 0)
694 if (token.type == end_token &&
695 parenthesis_count == 0 &&
709 * Eat input tokens until an anchor is found.
711 static void eat_until_anchor(void)
713 while (token_anchor_set[token.type] == 0) {
714 if (token.type == '(' || token.type == '{' || token.type == '[')
715 eat_until_matching_token(token.type);
720 static void eat_block(void)
722 eat_until_matching_token('{');
723 if (token.type == '}')
727 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
730 * Report a parse error because an expected token was not found.
733 #if defined __GNUC__ && __GNUC__ >= 4
734 __attribute__((sentinel))
736 void parse_error_expected(const char *message, ...)
738 if (message != NULL) {
739 errorf(HERE, "%s", message);
742 va_start(ap, message);
743 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
748 * Report a type error.
750 static void type_error(const char *msg, const source_position_t *source_position,
753 errorf(source_position, "%s, but found type '%T'", msg, type);
757 * Report an incompatible type.
759 static void type_error_incompatible(const char *msg,
760 const source_position_t *source_position, type_t *type1, type_t *type2)
762 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
767 * Expect the the current token is the expected token.
768 * If not, generate an error, eat the current statement,
769 * and goto the end_error label.
771 #define expect(expected) \
773 if (UNLIKELY(token.type != (expected))) { \
774 parse_error_expected(NULL, (expected), NULL); \
775 add_anchor_token(expected); \
776 eat_until_anchor(); \
777 if (token.type == expected) \
779 rem_anchor_token(expected); \
785 static void scope_push(scope_t *new_scope)
787 if (current_scope != NULL) {
788 new_scope->depth = current_scope->depth + 1;
790 new_scope->parent = current_scope;
791 current_scope = new_scope;
794 static void scope_pop(void)
796 current_scope = current_scope->parent;
800 * Search an entity by its symbol in a given namespace.
802 static entity_t *get_entity(const symbol_t *const symbol,
803 namespace_tag_t namespc)
805 entity_t *entity = symbol->entity;
806 for (; entity != NULL; entity = entity->base.symbol_next) {
807 if (entity->base.namespc == namespc)
815 * pushs an entity on the environment stack and links the corresponding symbol
818 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
820 symbol_t *symbol = entity->base.symbol;
821 entity_namespace_t namespc = entity->base.namespc;
822 assert(namespc != NAMESPACE_INVALID);
824 /* replace/add entity into entity list of the symbol */
827 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
832 /* replace an entry? */
833 if (iter->base.namespc == namespc) {
834 entity->base.symbol_next = iter->base.symbol_next;
840 /* remember old declaration */
842 entry.symbol = symbol;
843 entry.old_entity = iter;
844 entry.namespc = namespc;
845 ARR_APP1(stack_entry_t, *stack_ptr, entry);
849 * Push an entity on the environment stack.
851 static void environment_push(entity_t *entity)
853 assert(entity->base.source_position.input_name != NULL);
854 assert(entity->base.parent_scope != NULL);
855 stack_push(&environment_stack, entity);
859 * Push a declaration on the global label stack.
861 * @param declaration the declaration
863 static void label_push(entity_t *label)
865 /* we abuse the parameters scope as parent for the labels */
866 label->base.parent_scope = ¤t_function->parameters;
867 stack_push(&label_stack, label);
871 * pops symbols from the environment stack until @p new_top is the top element
873 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
875 stack_entry_t *stack = *stack_ptr;
876 size_t top = ARR_LEN(stack);
879 assert(new_top <= top);
883 for (i = top; i > new_top; --i) {
884 stack_entry_t *entry = &stack[i - 1];
886 entity_t *old_entity = entry->old_entity;
887 symbol_t *symbol = entry->symbol;
888 entity_namespace_t namespc = entry->namespc;
890 /* replace with old_entity/remove */
893 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
895 assert(iter != NULL);
896 /* replace an entry? */
897 if (iter->base.namespc == namespc)
901 /* restore definition from outer scopes (if there was one) */
902 if (old_entity != NULL) {
903 old_entity->base.symbol_next = iter->base.symbol_next;
904 *anchor = old_entity;
906 /* remove entry from list */
907 *anchor = iter->base.symbol_next;
911 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
915 * Pop all entries from the environment stack until the new_top
918 * @param new_top the new stack top
920 static void environment_pop_to(size_t new_top)
922 stack_pop_to(&environment_stack, new_top);
926 * Pop all entries from the global label stack until the new_top
929 * @param new_top the new stack top
931 static void label_pop_to(size_t new_top)
933 stack_pop_to(&label_stack, new_top);
936 static int get_akind_rank(atomic_type_kind_t akind)
941 static int get_rank(const type_t *type)
943 assert(!is_typeref(type));
944 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
945 * and esp. footnote 108). However we can't fold constants (yet), so we
946 * can't decide whether unsigned int is possible, while int always works.
947 * (unsigned int would be preferable when possible... for stuff like
948 * struct { enum { ... } bla : 4; } ) */
949 if (type->kind == TYPE_ENUM)
950 return get_akind_rank(ATOMIC_TYPE_INT);
952 assert(type->kind == TYPE_ATOMIC);
953 return get_akind_rank(type->atomic.akind);
956 static type_t *promote_integer(type_t *type)
958 if (type->kind == TYPE_BITFIELD)
959 type = type->bitfield.base_type;
961 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
968 * Create a cast expression.
970 * @param expression the expression to cast
971 * @param dest_type the destination type
973 static expression_t *create_cast_expression(expression_t *expression,
976 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
978 cast->unary.value = expression;
979 cast->base.type = dest_type;
985 * Check if a given expression represents the 0 pointer constant.
987 static bool is_null_pointer_constant(const expression_t *expression)
989 /* skip void* cast */
990 if (expression->kind == EXPR_UNARY_CAST
991 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
992 expression = expression->unary.value;
995 /* TODO: not correct yet, should be any constant integer expression
996 * which evaluates to 0 */
997 if (expression->kind != EXPR_CONST)
1000 type_t *const type = skip_typeref(expression->base.type);
1001 if (!is_type_integer(type))
1004 return expression->conste.v.int_value == 0;
1008 * Create an implicit cast expression.
1010 * @param expression the expression to cast
1011 * @param dest_type the destination type
1013 static expression_t *create_implicit_cast(expression_t *expression,
1016 type_t *const source_type = expression->base.type;
1018 if (source_type == dest_type)
1021 return create_cast_expression(expression, dest_type);
1024 typedef enum assign_error_t {
1026 ASSIGN_ERROR_INCOMPATIBLE,
1027 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1028 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1029 ASSIGN_WARNING_POINTER_FROM_INT,
1030 ASSIGN_WARNING_INT_FROM_POINTER
1033 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1034 const expression_t *const right,
1035 const char *context,
1036 const source_position_t *source_position)
1038 type_t *const orig_type_right = right->base.type;
1039 type_t *const type_left = skip_typeref(orig_type_left);
1040 type_t *const type_right = skip_typeref(orig_type_right);
1043 case ASSIGN_SUCCESS:
1045 case ASSIGN_ERROR_INCOMPATIBLE:
1046 errorf(source_position,
1047 "destination type '%T' in %s is incompatible with type '%T'",
1048 orig_type_left, context, orig_type_right);
1051 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1052 if (warning.other) {
1053 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1054 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1056 /* the left type has all qualifiers from the right type */
1057 unsigned missing_qualifiers
1058 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1059 warningf(source_position,
1060 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1061 orig_type_left, context, orig_type_right, missing_qualifiers);
1066 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1067 if (warning.other) {
1068 warningf(source_position,
1069 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1070 orig_type_left, context, right, orig_type_right);
1074 case ASSIGN_WARNING_POINTER_FROM_INT:
1075 if (warning.other) {
1076 warningf(source_position,
1077 "%s makes pointer '%T' from integer '%T' without a cast",
1078 context, orig_type_left, orig_type_right);
1082 case ASSIGN_WARNING_INT_FROM_POINTER:
1083 if (warning.other) {
1084 warningf(source_position,
1085 "%s makes integer '%T' from pointer '%T' without a cast",
1086 context, orig_type_left, orig_type_right);
1091 panic("invalid error value");
1095 /** Implements the rules from § 6.5.16.1 */
1096 static assign_error_t semantic_assign(type_t *orig_type_left,
1097 const expression_t *const right)
1099 type_t *const orig_type_right = right->base.type;
1100 type_t *const type_left = skip_typeref(orig_type_left);
1101 type_t *const type_right = skip_typeref(orig_type_right);
1103 if (is_type_pointer(type_left)) {
1104 if (is_null_pointer_constant(right)) {
1105 return ASSIGN_SUCCESS;
1106 } else if (is_type_pointer(type_right)) {
1107 type_t *points_to_left
1108 = skip_typeref(type_left->pointer.points_to);
1109 type_t *points_to_right
1110 = skip_typeref(type_right->pointer.points_to);
1111 assign_error_t res = ASSIGN_SUCCESS;
1113 /* the left type has all qualifiers from the right type */
1114 unsigned missing_qualifiers
1115 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1116 if (missing_qualifiers != 0) {
1117 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1120 points_to_left = get_unqualified_type(points_to_left);
1121 points_to_right = get_unqualified_type(points_to_right);
1123 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1126 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1127 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1128 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1131 if (!types_compatible(points_to_left, points_to_right)) {
1132 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1136 } else if (is_type_integer(type_right)) {
1137 return ASSIGN_WARNING_POINTER_FROM_INT;
1139 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1140 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1141 && is_type_pointer(type_right))) {
1142 return ASSIGN_SUCCESS;
1143 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1144 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1145 type_t *const unqual_type_left = get_unqualified_type(type_left);
1146 type_t *const unqual_type_right = get_unqualified_type(type_right);
1147 if (types_compatible(unqual_type_left, unqual_type_right)) {
1148 return ASSIGN_SUCCESS;
1150 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1151 return ASSIGN_WARNING_INT_FROM_POINTER;
1154 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1155 return ASSIGN_SUCCESS;
1157 return ASSIGN_ERROR_INCOMPATIBLE;
1160 static expression_t *parse_constant_expression(void)
1162 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1164 if (!is_constant_expression(result)) {
1165 errorf(&result->base.source_position,
1166 "expression '%E' is not constant\n", result);
1172 static expression_t *parse_assignment_expression(void)
1174 return parse_sub_expression(PREC_ASSIGNMENT);
1177 static string_t parse_string_literals(void)
1179 assert(token.type == T_STRING_LITERAL);
1180 string_t result = token.v.string;
1184 while (token.type == T_STRING_LITERAL) {
1185 result = concat_strings(&result, &token.v.string);
1192 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1193 [GNU_AK_CONST] = "const",
1194 [GNU_AK_VOLATILE] = "volatile",
1195 [GNU_AK_CDECL] = "cdecl",
1196 [GNU_AK_STDCALL] = "stdcall",
1197 [GNU_AK_FASTCALL] = "fastcall",
1198 [GNU_AK_DEPRECATED] = "deprecated",
1199 [GNU_AK_NOINLINE] = "noinline",
1200 [GNU_AK_NORETURN] = "noreturn",
1201 [GNU_AK_NAKED] = "naked",
1202 [GNU_AK_PURE] = "pure",
1203 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1204 [GNU_AK_MALLOC] = "malloc",
1205 [GNU_AK_WEAK] = "weak",
1206 [GNU_AK_CONSTRUCTOR] = "constructor",
1207 [GNU_AK_DESTRUCTOR] = "destructor",
1208 [GNU_AK_NOTHROW] = "nothrow",
1209 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1210 [GNU_AK_COMMON] = "common",
1211 [GNU_AK_NOCOMMON] = "nocommon",
1212 [GNU_AK_PACKED] = "packed",
1213 [GNU_AK_SHARED] = "shared",
1214 [GNU_AK_NOTSHARED] = "notshared",
1215 [GNU_AK_USED] = "used",
1216 [GNU_AK_UNUSED] = "unused",
1217 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1218 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1219 [GNU_AK_LONGCALL] = "longcall",
1220 [GNU_AK_SHORTCALL] = "shortcall",
1221 [GNU_AK_LONG_CALL] = "long_call",
1222 [GNU_AK_SHORT_CALL] = "short_call",
1223 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1224 [GNU_AK_INTERRUPT] = "interrupt",
1225 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1226 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1227 [GNU_AK_NESTING] = "nesting",
1228 [GNU_AK_NEAR] = "near",
1229 [GNU_AK_FAR] = "far",
1230 [GNU_AK_SIGNAL] = "signal",
1231 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1232 [GNU_AK_TINY_DATA] = "tiny_data",
1233 [GNU_AK_SAVEALL] = "saveall",
1234 [GNU_AK_FLATTEN] = "flatten",
1235 [GNU_AK_SSEREGPARM] = "sseregparm",
1236 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1237 [GNU_AK_RETURN_TWICE] = "return_twice",
1238 [GNU_AK_MAY_ALIAS] = "may_alias",
1239 [GNU_AK_MS_STRUCT] = "ms_struct",
1240 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1241 [GNU_AK_DLLIMPORT] = "dllimport",
1242 [GNU_AK_DLLEXPORT] = "dllexport",
1243 [GNU_AK_ALIGNED] = "aligned",
1244 [GNU_AK_ALIAS] = "alias",
1245 [GNU_AK_SECTION] = "section",
1246 [GNU_AK_FORMAT] = "format",
1247 [GNU_AK_FORMAT_ARG] = "format_arg",
1248 [GNU_AK_WEAKREF] = "weakref",
1249 [GNU_AK_NONNULL] = "nonnull",
1250 [GNU_AK_TLS_MODEL] = "tls_model",
1251 [GNU_AK_VISIBILITY] = "visibility",
1252 [GNU_AK_REGPARM] = "regparm",
1253 [GNU_AK_MODE] = "mode",
1254 [GNU_AK_MODEL] = "model",
1255 [GNU_AK_TRAP_EXIT] = "trap_exit",
1256 [GNU_AK_SP_SWITCH] = "sp_switch",
1257 [GNU_AK_SENTINEL] = "sentinel"
1261 * compare two string, ignoring double underscores on the second.
1263 static int strcmp_underscore(const char *s1, const char *s2)
1265 if (s2[0] == '_' && s2[1] == '_') {
1266 size_t len2 = strlen(s2);
1267 size_t len1 = strlen(s1);
1268 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1269 return strncmp(s1, s2+2, len2-4);
1273 return strcmp(s1, s2);
1277 * Allocate a new gnu temporal attribute.
1279 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1281 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1282 attribute->kind = kind;
1283 attribute->next = NULL;
1284 attribute->invalid = false;
1285 attribute->have_arguments = false;
1291 * parse one constant expression argument.
1293 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1295 expression_t *expression;
1296 add_anchor_token(')');
1297 expression = parse_constant_expression();
1298 rem_anchor_token(')');
1300 attribute->u.argument = fold_constant(expression);
1303 attribute->invalid = true;
1307 * parse a list of constant expressions arguments.
1309 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1311 argument_list_t **list = &attribute->u.arguments;
1312 argument_list_t *entry;
1313 expression_t *expression;
1314 add_anchor_token(')');
1315 add_anchor_token(',');
1317 expression = parse_constant_expression();
1318 entry = obstack_alloc(&temp_obst, sizeof(entry));
1319 entry->argument = fold_constant(expression);
1322 list = &entry->next;
1323 if (token.type != ',')
1327 rem_anchor_token(',');
1328 rem_anchor_token(')');
1332 attribute->invalid = true;
1336 * parse one string literal argument.
1338 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1341 add_anchor_token('(');
1342 if (token.type != T_STRING_LITERAL) {
1343 parse_error_expected("while parsing attribute directive",
1344 T_STRING_LITERAL, NULL);
1347 *string = parse_string_literals();
1348 rem_anchor_token('(');
1352 attribute->invalid = true;
1356 * parse one tls model.
1358 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1360 static const char *const tls_models[] = {
1366 string_t string = { NULL, 0 };
1367 parse_gnu_attribute_string_arg(attribute, &string);
1368 if (string.begin != NULL) {
1369 for (size_t i = 0; i < 4; ++i) {
1370 if (strcmp(tls_models[i], string.begin) == 0) {
1371 attribute->u.value = i;
1375 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1377 attribute->invalid = true;
1381 * parse one tls model.
1383 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1385 static const char *const visibilities[] = {
1391 string_t string = { NULL, 0 };
1392 parse_gnu_attribute_string_arg(attribute, &string);
1393 if (string.begin != NULL) {
1394 for (size_t i = 0; i < 4; ++i) {
1395 if (strcmp(visibilities[i], string.begin) == 0) {
1396 attribute->u.value = i;
1400 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1402 attribute->invalid = true;
1406 * parse one (code) model.
1408 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1410 static const char *const visibilities[] = {
1415 string_t string = { NULL, 0 };
1416 parse_gnu_attribute_string_arg(attribute, &string);
1417 if (string.begin != NULL) {
1418 for (int i = 0; i < 3; ++i) {
1419 if (strcmp(visibilities[i], string.begin) == 0) {
1420 attribute->u.value = i;
1424 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1426 attribute->invalid = true;
1429 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1431 /* TODO: find out what is allowed here... */
1433 /* at least: byte, word, pointer, list of machine modes
1434 * __XXX___ is interpreted as XXX */
1435 add_anchor_token(')');
1437 if (token.type != T_IDENTIFIER) {
1438 expect(T_IDENTIFIER);
1441 /* This isn't really correct, the backend should provide a list of machine
1442 * specific modes (according to gcc philosophy that is...) */
1443 const char *symbol_str = token.v.symbol->string;
1444 if (strcmp_underscore("QI", symbol_str) == 0 ||
1445 strcmp_underscore("byte", symbol_str) == 0) {
1446 attribute->u.akind = ATOMIC_TYPE_CHAR;
1447 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1448 attribute->u.akind = ATOMIC_TYPE_SHORT;
1449 } else if (strcmp_underscore("SI", symbol_str) == 0
1450 || strcmp_underscore("word", symbol_str) == 0
1451 || strcmp_underscore("pointer", symbol_str) == 0) {
1452 attribute->u.akind = ATOMIC_TYPE_INT;
1453 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1454 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1457 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1458 attribute->invalid = true;
1462 rem_anchor_token(')');
1466 attribute->invalid = true;
1470 * parse one interrupt argument.
1472 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1474 static const char *const interrupts[] = {
1481 string_t string = { NULL, 0 };
1482 parse_gnu_attribute_string_arg(attribute, &string);
1483 if (string.begin != NULL) {
1484 for (size_t i = 0; i < 5; ++i) {
1485 if (strcmp(interrupts[i], string.begin) == 0) {
1486 attribute->u.value = i;
1490 errorf(HERE, "'%s' is not an interrupt", string.begin);
1492 attribute->invalid = true;
1496 * parse ( identifier, const expression, const expression )
1498 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1500 static const char *const format_names[] = {
1508 if (token.type != T_IDENTIFIER) {
1509 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1512 const char *name = token.v.symbol->string;
1513 for (i = 0; i < 4; ++i) {
1514 if (strcmp_underscore(format_names[i], name) == 0)
1518 if (warning.attribute)
1519 warningf(HERE, "'%s' is an unrecognized format function type", name);
1524 add_anchor_token(')');
1525 add_anchor_token(',');
1526 parse_constant_expression();
1527 rem_anchor_token(',');
1528 rem_anchor_token(')');
1531 add_anchor_token(')');
1532 parse_constant_expression();
1533 rem_anchor_token(')');
1537 attribute->u.value = true;
1540 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1542 if (!attribute->have_arguments)
1545 /* should have no arguments */
1546 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1547 eat_until_matching_token('(');
1548 /* we have already consumed '(', so we stop before ')', eat it */
1550 attribute->invalid = true;
1554 * Parse one GNU attribute.
1556 * Note that attribute names can be specified WITH or WITHOUT
1557 * double underscores, ie const or __const__.
1559 * The following attributes are parsed without arguments
1584 * no_instrument_function
1585 * warn_unused_result
1602 * externally_visible
1610 * The following attributes are parsed with arguments
1611 * aligned( const expression )
1612 * alias( string literal )
1613 * section( string literal )
1614 * format( identifier, const expression, const expression )
1615 * format_arg( const expression )
1616 * tls_model( string literal )
1617 * visibility( string literal )
1618 * regparm( const expression )
1619 * model( string leteral )
1620 * trap_exit( const expression )
1621 * sp_switch( string literal )
1623 * The following attributes might have arguments
1624 * weak_ref( string literal )
1625 * non_null( const expression // ',' )
1626 * interrupt( string literal )
1627 * sentinel( constant expression )
1629 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1631 gnu_attribute_t *head = *attributes;
1632 gnu_attribute_t *last = *attributes;
1633 decl_modifiers_t modifiers = 0;
1634 gnu_attribute_t *attribute;
1636 eat(T___attribute__);
1640 if (token.type != ')') {
1641 /* find the end of the list */
1643 while (last->next != NULL)
1647 /* non-empty attribute list */
1650 if (token.type == T_const) {
1652 } else if (token.type == T_volatile) {
1654 } else if (token.type == T_cdecl) {
1655 /* __attribute__((cdecl)), WITH ms mode */
1657 } else if (token.type == T_IDENTIFIER) {
1658 const symbol_t *sym = token.v.symbol;
1661 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1668 for (i = 0; i < GNU_AK_LAST; ++i) {
1669 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1672 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1675 if (kind == GNU_AK_LAST) {
1676 if (warning.attribute)
1677 warningf(HERE, "'%s' attribute directive ignored", name);
1679 /* skip possible arguments */
1680 if (token.type == '(') {
1681 eat_until_matching_token(')');
1684 /* check for arguments */
1685 attribute = allocate_gnu_attribute(kind);
1686 if (token.type == '(') {
1688 if (token.type == ')') {
1689 /* empty args are allowed */
1692 attribute->have_arguments = true;
1696 case GNU_AK_VOLATILE:
1701 case GNU_AK_NOCOMMON:
1703 case GNU_AK_NOTSHARED:
1704 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1705 case GNU_AK_WARN_UNUSED_RESULT:
1706 case GNU_AK_LONGCALL:
1707 case GNU_AK_SHORTCALL:
1708 case GNU_AK_LONG_CALL:
1709 case GNU_AK_SHORT_CALL:
1710 case GNU_AK_FUNCTION_VECTOR:
1711 case GNU_AK_INTERRUPT_HANDLER:
1712 case GNU_AK_NMI_HANDLER:
1713 case GNU_AK_NESTING:
1717 case GNU_AK_EIGTHBIT_DATA:
1718 case GNU_AK_TINY_DATA:
1719 case GNU_AK_SAVEALL:
1720 case GNU_AK_FLATTEN:
1721 case GNU_AK_SSEREGPARM:
1722 case GNU_AK_EXTERNALLY_VISIBLE:
1723 case GNU_AK_RETURN_TWICE:
1724 case GNU_AK_MAY_ALIAS:
1725 case GNU_AK_MS_STRUCT:
1726 case GNU_AK_GCC_STRUCT:
1729 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1730 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1731 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1732 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1733 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1734 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1735 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1736 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1737 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1738 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1739 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1740 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1741 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1742 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1743 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1744 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1745 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1746 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1748 case GNU_AK_ALIGNED:
1749 /* __align__ may be used without an argument */
1750 if (attribute->have_arguments) {
1751 parse_gnu_attribute_const_arg(attribute);
1755 case GNU_AK_FORMAT_ARG:
1756 case GNU_AK_REGPARM:
1757 case GNU_AK_TRAP_EXIT:
1758 if (!attribute->have_arguments) {
1759 /* should have arguments */
1760 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1761 attribute->invalid = true;
1763 parse_gnu_attribute_const_arg(attribute);
1766 case GNU_AK_SECTION:
1767 case GNU_AK_SP_SWITCH:
1768 if (!attribute->have_arguments) {
1769 /* should have arguments */
1770 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1771 attribute->invalid = true;
1773 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1776 if (!attribute->have_arguments) {
1777 /* should have arguments */
1778 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1779 attribute->invalid = true;
1781 parse_gnu_attribute_format_args(attribute);
1783 case GNU_AK_WEAKREF:
1784 /* may have one string argument */
1785 if (attribute->have_arguments)
1786 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1788 case GNU_AK_NONNULL:
1789 if (attribute->have_arguments)
1790 parse_gnu_attribute_const_arg_list(attribute);
1792 case GNU_AK_TLS_MODEL:
1793 if (!attribute->have_arguments) {
1794 /* should have arguments */
1795 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1797 parse_gnu_attribute_tls_model_arg(attribute);
1799 case GNU_AK_VISIBILITY:
1800 if (!attribute->have_arguments) {
1801 /* should have arguments */
1802 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1804 parse_gnu_attribute_visibility_arg(attribute);
1807 if (!attribute->have_arguments) {
1808 /* should have arguments */
1809 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1811 parse_gnu_attribute_model_arg(attribute);
1815 if (!attribute->have_arguments) {
1816 /* should have arguments */
1817 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1819 parse_gnu_attribute_mode_arg(attribute);
1822 case GNU_AK_INTERRUPT:
1823 /* may have one string argument */
1824 if (attribute->have_arguments)
1825 parse_gnu_attribute_interrupt_arg(attribute);
1827 case GNU_AK_SENTINEL:
1828 /* may have one string argument */
1829 if (attribute->have_arguments)
1830 parse_gnu_attribute_const_arg(attribute);
1833 /* already handled */
1837 check_no_argument(attribute, name);
1840 if (attribute != NULL) {
1842 last->next = attribute;
1845 head = last = attribute;
1849 if (token.type != ',')
1863 * Parse GNU attributes.
1865 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1867 decl_modifiers_t modifiers = 0;
1870 switch (token.type) {
1871 case T___attribute__:
1872 modifiers |= parse_gnu_attribute(attributes);
1878 if (token.type != T_STRING_LITERAL) {
1879 parse_error_expected("while parsing assembler attribute",
1880 T_STRING_LITERAL, NULL);
1881 eat_until_matching_token('(');
1884 parse_string_literals();
1889 case T_cdecl: modifiers |= DM_CDECL; break;
1890 case T__fastcall: modifiers |= DM_FASTCALL; break;
1891 case T__stdcall: modifiers |= DM_STDCALL; break;
1894 /* TODO record modifier */
1896 warningf(HERE, "Ignoring declaration modifier %K", &token);
1900 default: return modifiers;
1907 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1909 static variable_t *determine_lhs_var(expression_t *const expr,
1910 variable_t *lhs_var)
1912 switch (expr->kind) {
1913 case EXPR_REFERENCE: {
1914 entity_t *const entity = expr->reference.entity;
1915 /* we should only find variables as lavlues... */
1916 if (entity->base.kind != ENTITY_VARIABLE)
1919 return &entity->variable;
1922 case EXPR_ARRAY_ACCESS: {
1923 expression_t *const ref = expr->array_access.array_ref;
1924 variable_t * var = NULL;
1925 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1926 var = determine_lhs_var(ref, lhs_var);
1929 mark_vars_read(expr->select.compound, lhs_var);
1931 mark_vars_read(expr->array_access.index, lhs_var);
1936 if (is_type_compound(skip_typeref(expr->base.type))) {
1937 return determine_lhs_var(expr->select.compound, lhs_var);
1939 mark_vars_read(expr->select.compound, lhs_var);
1944 case EXPR_UNARY_DEREFERENCE: {
1945 expression_t *const val = expr->unary.value;
1946 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1948 return determine_lhs_var(val->unary.value, lhs_var);
1950 mark_vars_read(val, NULL);
1956 mark_vars_read(expr, NULL);
1961 #define VAR_ANY ((variable_t*)-1)
1964 * Mark declarations, which are read. This is used to deted variables, which
1968 * x is not marked as "read", because it is only read to calculate its own new
1972 * x and y are not detected as "not read", because multiple variables are
1975 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1977 switch (expr->kind) {
1978 case EXPR_REFERENCE: {
1979 entity_t *const entity = expr->reference.entity;
1980 if (entity->kind != ENTITY_VARIABLE)
1983 variable_t *variable = &entity->variable;
1984 if (lhs_var != variable && lhs_var != VAR_ANY) {
1985 variable->read = true;
1991 // TODO respect pure/const
1992 mark_vars_read(expr->call.function, NULL);
1993 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1994 mark_vars_read(arg->expression, NULL);
1998 case EXPR_CONDITIONAL:
1999 // TODO lhs_decl should depend on whether true/false have an effect
2000 mark_vars_read(expr->conditional.condition, NULL);
2001 if (expr->conditional.true_expression != NULL)
2002 mark_vars_read(expr->conditional.true_expression, lhs_var);
2003 mark_vars_read(expr->conditional.false_expression, lhs_var);
2007 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2009 mark_vars_read(expr->select.compound, lhs_var);
2012 case EXPR_ARRAY_ACCESS: {
2013 expression_t *const ref = expr->array_access.array_ref;
2014 mark_vars_read(ref, lhs_var);
2015 lhs_var = determine_lhs_var(ref, lhs_var);
2016 mark_vars_read(expr->array_access.index, lhs_var);
2021 mark_vars_read(expr->va_arge.ap, lhs_var);
2024 case EXPR_UNARY_CAST:
2025 /* Special case: Use void cast to mark a variable as "read" */
2026 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2031 case EXPR_UNARY_THROW:
2032 if (expr->unary.value == NULL)
2035 case EXPR_UNARY_DEREFERENCE:
2036 case EXPR_UNARY_DELETE:
2037 case EXPR_UNARY_DELETE_ARRAY:
2038 if (lhs_var == VAR_ANY)
2042 case EXPR_UNARY_NEGATE:
2043 case EXPR_UNARY_PLUS:
2044 case EXPR_UNARY_BITWISE_NEGATE:
2045 case EXPR_UNARY_NOT:
2046 case EXPR_UNARY_TAKE_ADDRESS:
2047 case EXPR_UNARY_POSTFIX_INCREMENT:
2048 case EXPR_UNARY_POSTFIX_DECREMENT:
2049 case EXPR_UNARY_PREFIX_INCREMENT:
2050 case EXPR_UNARY_PREFIX_DECREMENT:
2051 case EXPR_UNARY_CAST_IMPLICIT:
2052 case EXPR_UNARY_ASSUME:
2054 mark_vars_read(expr->unary.value, lhs_var);
2057 case EXPR_BINARY_ADD:
2058 case EXPR_BINARY_SUB:
2059 case EXPR_BINARY_MUL:
2060 case EXPR_BINARY_DIV:
2061 case EXPR_BINARY_MOD:
2062 case EXPR_BINARY_EQUAL:
2063 case EXPR_BINARY_NOTEQUAL:
2064 case EXPR_BINARY_LESS:
2065 case EXPR_BINARY_LESSEQUAL:
2066 case EXPR_BINARY_GREATER:
2067 case EXPR_BINARY_GREATEREQUAL:
2068 case EXPR_BINARY_BITWISE_AND:
2069 case EXPR_BINARY_BITWISE_OR:
2070 case EXPR_BINARY_BITWISE_XOR:
2071 case EXPR_BINARY_LOGICAL_AND:
2072 case EXPR_BINARY_LOGICAL_OR:
2073 case EXPR_BINARY_SHIFTLEFT:
2074 case EXPR_BINARY_SHIFTRIGHT:
2075 case EXPR_BINARY_COMMA:
2076 case EXPR_BINARY_ISGREATER:
2077 case EXPR_BINARY_ISGREATEREQUAL:
2078 case EXPR_BINARY_ISLESS:
2079 case EXPR_BINARY_ISLESSEQUAL:
2080 case EXPR_BINARY_ISLESSGREATER:
2081 case EXPR_BINARY_ISUNORDERED:
2082 mark_vars_read(expr->binary.left, lhs_var);
2083 mark_vars_read(expr->binary.right, lhs_var);
2086 case EXPR_BINARY_ASSIGN:
2087 case EXPR_BINARY_MUL_ASSIGN:
2088 case EXPR_BINARY_DIV_ASSIGN:
2089 case EXPR_BINARY_MOD_ASSIGN:
2090 case EXPR_BINARY_ADD_ASSIGN:
2091 case EXPR_BINARY_SUB_ASSIGN:
2092 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2093 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2094 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2095 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2096 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2097 if (lhs_var == VAR_ANY)
2099 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2100 mark_vars_read(expr->binary.right, lhs_var);
2105 determine_lhs_var(expr->va_starte.ap, lhs_var);
2111 case EXPR_CHARACTER_CONSTANT:
2112 case EXPR_WIDE_CHARACTER_CONSTANT:
2113 case EXPR_STRING_LITERAL:
2114 case EXPR_WIDE_STRING_LITERAL:
2115 case EXPR_COMPOUND_LITERAL: // TODO init?
2117 case EXPR_CLASSIFY_TYPE:
2120 case EXPR_BUILTIN_SYMBOL:
2121 case EXPR_BUILTIN_CONSTANT_P:
2122 case EXPR_BUILTIN_PREFETCH:
2124 case EXPR_STATEMENT: // TODO
2125 case EXPR_LABEL_ADDRESS:
2126 case EXPR_BINARY_BUILTIN_EXPECT:
2127 case EXPR_REFERENCE_ENUM_VALUE:
2131 panic("unhandled expression");
2134 static designator_t *parse_designation(void)
2136 designator_t *result = NULL;
2137 designator_t *last = NULL;
2140 designator_t *designator;
2141 switch (token.type) {
2143 designator = allocate_ast_zero(sizeof(designator[0]));
2144 designator->source_position = token.source_position;
2146 add_anchor_token(']');
2147 designator->array_index = parse_constant_expression();
2148 rem_anchor_token(']');
2152 designator = allocate_ast_zero(sizeof(designator[0]));
2153 designator->source_position = token.source_position;
2155 if (token.type != T_IDENTIFIER) {
2156 parse_error_expected("while parsing designator",
2157 T_IDENTIFIER, NULL);
2160 designator->symbol = token.v.symbol;
2168 assert(designator != NULL);
2170 last->next = designator;
2172 result = designator;
2180 static initializer_t *initializer_from_string(array_type_t *type,
2181 const string_t *const string)
2183 /* TODO: check len vs. size of array type */
2186 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2187 initializer->string.string = *string;
2192 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2193 wide_string_t *const string)
2195 /* TODO: check len vs. size of array type */
2198 initializer_t *const initializer =
2199 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2200 initializer->wide_string.string = *string;
2206 * Build an initializer from a given expression.
2208 static initializer_t *initializer_from_expression(type_t *orig_type,
2209 expression_t *expression)
2211 /* TODO check that expression is a constant expression */
2213 /* § 6.7.8.14/15 char array may be initialized by string literals */
2214 type_t *type = skip_typeref(orig_type);
2215 type_t *expr_type_orig = expression->base.type;
2216 type_t *expr_type = skip_typeref(expr_type_orig);
2217 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2218 array_type_t *const array_type = &type->array;
2219 type_t *const element_type = skip_typeref(array_type->element_type);
2221 if (element_type->kind == TYPE_ATOMIC) {
2222 atomic_type_kind_t akind = element_type->atomic.akind;
2223 switch (expression->kind) {
2224 case EXPR_STRING_LITERAL:
2225 if (akind == ATOMIC_TYPE_CHAR
2226 || akind == ATOMIC_TYPE_SCHAR
2227 || akind == ATOMIC_TYPE_UCHAR) {
2228 return initializer_from_string(array_type,
2229 &expression->string.value);
2232 case EXPR_WIDE_STRING_LITERAL: {
2233 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2234 if (get_unqualified_type(element_type) == bare_wchar_type) {
2235 return initializer_from_wide_string(array_type,
2236 &expression->wide_string.value);
2246 assign_error_t error = semantic_assign(type, expression);
2247 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2249 report_assign_error(error, type, expression, "initializer",
2250 &expression->base.source_position);
2252 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2254 if (type->kind == TYPE_BITFIELD) {
2255 type = type->bitfield.base_type;
2258 result->value.value = create_implicit_cast(expression, type);
2264 * Checks if a given expression can be used as an constant initializer.
2266 static bool is_initializer_constant(const expression_t *expression)
2268 return is_constant_expression(expression)
2269 || is_address_constant(expression);
2273 * Parses an scalar initializer.
2275 * § 6.7.8.11; eat {} without warning
2277 static initializer_t *parse_scalar_initializer(type_t *type,
2278 bool must_be_constant)
2280 /* there might be extra {} hierarchies */
2282 if (token.type == '{') {
2284 warningf(HERE, "extra curly braces around scalar initializer");
2288 } while (token.type == '{');
2291 expression_t *expression = parse_assignment_expression();
2292 mark_vars_read(expression, NULL);
2293 if (must_be_constant && !is_initializer_constant(expression)) {
2294 errorf(&expression->base.source_position,
2295 "Initialisation expression '%E' is not constant\n",
2299 initializer_t *initializer = initializer_from_expression(type, expression);
2301 if (initializer == NULL) {
2302 errorf(&expression->base.source_position,
2303 "expression '%E' (type '%T') doesn't match expected type '%T'",
2304 expression, expression->base.type, type);
2309 bool additional_warning_displayed = false;
2310 while (braces > 0) {
2311 if (token.type == ',') {
2314 if (token.type != '}') {
2315 if (!additional_warning_displayed && warning.other) {
2316 warningf(HERE, "additional elements in scalar initializer");
2317 additional_warning_displayed = true;
2328 * An entry in the type path.
2330 typedef struct type_path_entry_t type_path_entry_t;
2331 struct type_path_entry_t {
2332 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2334 size_t index; /**< For array types: the current index. */
2335 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2340 * A type path expression a position inside compound or array types.
2342 typedef struct type_path_t type_path_t;
2343 struct type_path_t {
2344 type_path_entry_t *path; /**< An flexible array containing the current path. */
2345 type_t *top_type; /**< type of the element the path points */
2346 size_t max_index; /**< largest index in outermost array */
2350 * Prints a type path for debugging.
2352 static __attribute__((unused)) void debug_print_type_path(
2353 const type_path_t *path)
2355 size_t len = ARR_LEN(path->path);
2357 for (size_t i = 0; i < len; ++i) {
2358 const type_path_entry_t *entry = & path->path[i];
2360 type_t *type = skip_typeref(entry->type);
2361 if (is_type_compound(type)) {
2362 /* in gcc mode structs can have no members */
2363 if (entry->v.compound_entry == NULL) {
2367 fprintf(stderr, ".%s",
2368 entry->v.compound_entry->base.symbol->string);
2369 } else if (is_type_array(type)) {
2370 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2372 fprintf(stderr, "-INVALID-");
2375 if (path->top_type != NULL) {
2376 fprintf(stderr, " (");
2377 print_type(path->top_type);
2378 fprintf(stderr, ")");
2383 * Return the top type path entry, ie. in a path
2384 * (type).a.b returns the b.
2386 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2388 size_t len = ARR_LEN(path->path);
2390 return &path->path[len-1];
2394 * Enlarge the type path by an (empty) element.
2396 static type_path_entry_t *append_to_type_path(type_path_t *path)
2398 size_t len = ARR_LEN(path->path);
2399 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2401 type_path_entry_t *result = & path->path[len];
2402 memset(result, 0, sizeof(result[0]));
2407 * Descending into a sub-type. Enter the scope of the current top_type.
2409 static void descend_into_subtype(type_path_t *path)
2411 type_t *orig_top_type = path->top_type;
2412 type_t *top_type = skip_typeref(orig_top_type);
2414 type_path_entry_t *top = append_to_type_path(path);
2415 top->type = top_type;
2417 if (is_type_compound(top_type)) {
2418 compound_t *compound = top_type->compound.compound;
2419 entity_t *entry = compound->members.entities;
2421 if (entry != NULL) {
2422 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2423 top->v.compound_entry = &entry->declaration;
2424 path->top_type = entry->declaration.type;
2426 path->top_type = NULL;
2428 } else if (is_type_array(top_type)) {
2430 path->top_type = top_type->array.element_type;
2432 assert(!is_type_valid(top_type));
2437 * Pop an entry from the given type path, ie. returning from
2438 * (type).a.b to (type).a
2440 static void ascend_from_subtype(type_path_t *path)
2442 type_path_entry_t *top = get_type_path_top(path);
2444 path->top_type = top->type;
2446 size_t len = ARR_LEN(path->path);
2447 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2451 * Pop entries from the given type path until the given
2452 * path level is reached.
2454 static void ascend_to(type_path_t *path, size_t top_path_level)
2456 size_t len = ARR_LEN(path->path);
2458 while (len > top_path_level) {
2459 ascend_from_subtype(path);
2460 len = ARR_LEN(path->path);
2464 static bool walk_designator(type_path_t *path, const designator_t *designator,
2465 bool used_in_offsetof)
2467 for (; designator != NULL; designator = designator->next) {
2468 type_path_entry_t *top = get_type_path_top(path);
2469 type_t *orig_type = top->type;
2471 type_t *type = skip_typeref(orig_type);
2473 if (designator->symbol != NULL) {
2474 symbol_t *symbol = designator->symbol;
2475 if (!is_type_compound(type)) {
2476 if (is_type_valid(type)) {
2477 errorf(&designator->source_position,
2478 "'.%Y' designator used for non-compound type '%T'",
2482 top->type = type_error_type;
2483 top->v.compound_entry = NULL;
2484 orig_type = type_error_type;
2486 compound_t *compound = type->compound.compound;
2487 entity_t *iter = compound->members.entities;
2488 for (; iter != NULL; iter = iter->base.next) {
2489 if (iter->base.symbol == symbol) {
2494 errorf(&designator->source_position,
2495 "'%T' has no member named '%Y'", orig_type, symbol);
2498 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2499 if (used_in_offsetof) {
2500 type_t *real_type = skip_typeref(iter->declaration.type);
2501 if (real_type->kind == TYPE_BITFIELD) {
2502 errorf(&designator->source_position,
2503 "offsetof designator '%Y' may not specify bitfield",
2509 top->type = orig_type;
2510 top->v.compound_entry = &iter->declaration;
2511 orig_type = iter->declaration.type;
2514 expression_t *array_index = designator->array_index;
2515 assert(designator->array_index != NULL);
2517 if (!is_type_array(type)) {
2518 if (is_type_valid(type)) {
2519 errorf(&designator->source_position,
2520 "[%E] designator used for non-array type '%T'",
2521 array_index, orig_type);
2526 long index = fold_constant(array_index);
2527 if (!used_in_offsetof) {
2529 errorf(&designator->source_position,
2530 "array index [%E] must be positive", array_index);
2531 } else if (type->array.size_constant) {
2532 long array_size = type->array.size;
2533 if (index >= array_size) {
2534 errorf(&designator->source_position,
2535 "designator [%E] (%d) exceeds array size %d",
2536 array_index, index, array_size);
2541 top->type = orig_type;
2542 top->v.index = (size_t) index;
2543 orig_type = type->array.element_type;
2545 path->top_type = orig_type;
2547 if (designator->next != NULL) {
2548 descend_into_subtype(path);
2557 static void advance_current_object(type_path_t *path, size_t top_path_level)
2559 type_path_entry_t *top = get_type_path_top(path);
2561 type_t *type = skip_typeref(top->type);
2562 if (is_type_union(type)) {
2563 /* in unions only the first element is initialized */
2564 top->v.compound_entry = NULL;
2565 } else if (is_type_struct(type)) {
2566 declaration_t *entry = top->v.compound_entry;
2568 entity_t *next_entity = entry->base.next;
2569 if (next_entity != NULL) {
2570 assert(is_declaration(next_entity));
2571 entry = &next_entity->declaration;
2576 top->v.compound_entry = entry;
2577 if (entry != NULL) {
2578 path->top_type = entry->type;
2581 } else if (is_type_array(type)) {
2582 assert(is_type_array(type));
2586 if (!type->array.size_constant || top->v.index < type->array.size) {
2590 assert(!is_type_valid(type));
2594 /* we're past the last member of the current sub-aggregate, try if we
2595 * can ascend in the type hierarchy and continue with another subobject */
2596 size_t len = ARR_LEN(path->path);
2598 if (len > top_path_level) {
2599 ascend_from_subtype(path);
2600 advance_current_object(path, top_path_level);
2602 path->top_type = NULL;
2607 * skip until token is found.
2609 static void skip_until(int type)
2611 while (token.type != type) {
2612 if (token.type == T_EOF)
2619 * skip any {...} blocks until a closing bracket is reached.
2621 static void skip_initializers(void)
2623 if (token.type == '{')
2626 while (token.type != '}') {
2627 if (token.type == T_EOF)
2629 if (token.type == '{') {
2637 static initializer_t *create_empty_initializer(void)
2639 static initializer_t empty_initializer
2640 = { .list = { { INITIALIZER_LIST }, 0 } };
2641 return &empty_initializer;
2645 * Parse a part of an initialiser for a struct or union,
2647 static initializer_t *parse_sub_initializer(type_path_t *path,
2648 type_t *outer_type, size_t top_path_level,
2649 parse_initializer_env_t *env)
2651 if (token.type == '}') {
2652 /* empty initializer */
2653 return create_empty_initializer();
2656 type_t *orig_type = path->top_type;
2657 type_t *type = NULL;
2659 if (orig_type == NULL) {
2660 /* We are initializing an empty compound. */
2662 type = skip_typeref(orig_type);
2665 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2668 designator_t *designator = NULL;
2669 if (token.type == '.' || token.type == '[') {
2670 designator = parse_designation();
2671 goto finish_designator;
2672 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2673 /* GNU-style designator ("identifier: value") */
2674 designator = allocate_ast_zero(sizeof(designator[0]));
2675 designator->source_position = token.source_position;
2676 designator->symbol = token.v.symbol;
2681 /* reset path to toplevel, evaluate designator from there */
2682 ascend_to(path, top_path_level);
2683 if (!walk_designator(path, designator, false)) {
2684 /* can't continue after designation error */
2688 initializer_t *designator_initializer
2689 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2690 designator_initializer->designator.designator = designator;
2691 ARR_APP1(initializer_t*, initializers, designator_initializer);
2693 orig_type = path->top_type;
2694 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2699 if (token.type == '{') {
2700 if (type != NULL && is_type_scalar(type)) {
2701 sub = parse_scalar_initializer(type, env->must_be_constant);
2705 if (env->entity != NULL) {
2707 "extra brace group at end of initializer for '%Y'",
2708 env->entity->base.symbol);
2710 errorf(HERE, "extra brace group at end of initializer");
2713 descend_into_subtype(path);
2715 add_anchor_token('}');
2716 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2718 rem_anchor_token('}');
2721 ascend_from_subtype(path);
2725 goto error_parse_next;
2729 /* must be an expression */
2730 expression_t *expression = parse_assignment_expression();
2732 if (env->must_be_constant && !is_initializer_constant(expression)) {
2733 errorf(&expression->base.source_position,
2734 "Initialisation expression '%E' is not constant\n",
2739 /* we are already outside, ... */
2740 type_t *const outer_type_skip = skip_typeref(outer_type);
2741 if (is_type_compound(outer_type_skip) &&
2742 !outer_type_skip->compound.compound->complete) {
2743 goto error_parse_next;
2748 /* handle { "string" } special case */
2749 if ((expression->kind == EXPR_STRING_LITERAL
2750 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2751 && outer_type != NULL) {
2752 sub = initializer_from_expression(outer_type, expression);
2754 if (token.type == ',') {
2757 if (token.type != '}' && warning.other) {
2758 warningf(HERE, "excessive elements in initializer for type '%T'",
2761 /* TODO: eat , ... */
2766 /* descend into subtypes until expression matches type */
2768 orig_type = path->top_type;
2769 type = skip_typeref(orig_type);
2771 sub = initializer_from_expression(orig_type, expression);
2775 if (!is_type_valid(type)) {
2778 if (is_type_scalar(type)) {
2779 errorf(&expression->base.source_position,
2780 "expression '%E' doesn't match expected type '%T'",
2781 expression, orig_type);
2785 descend_into_subtype(path);
2789 /* update largest index of top array */
2790 const type_path_entry_t *first = &path->path[0];
2791 type_t *first_type = first->type;
2792 first_type = skip_typeref(first_type);
2793 if (is_type_array(first_type)) {
2794 size_t index = first->v.index;
2795 if (index > path->max_index)
2796 path->max_index = index;
2800 /* append to initializers list */
2801 ARR_APP1(initializer_t*, initializers, sub);
2804 if (warning.other) {
2805 if (env->entity != NULL) {
2806 warningf(HERE, "excess elements in struct initializer for '%Y'",
2807 env->entity->base.symbol);
2809 warningf(HERE, "excess elements in struct initializer");
2815 if (token.type == '}') {
2819 if (token.type == '}') {
2824 /* advance to the next declaration if we are not at the end */
2825 advance_current_object(path, top_path_level);
2826 orig_type = path->top_type;
2827 if (orig_type != NULL)
2828 type = skip_typeref(orig_type);
2834 size_t len = ARR_LEN(initializers);
2835 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2836 initializer_t *result = allocate_ast_zero(size);
2837 result->kind = INITIALIZER_LIST;
2838 result->list.len = len;
2839 memcpy(&result->list.initializers, initializers,
2840 len * sizeof(initializers[0]));
2842 DEL_ARR_F(initializers);
2843 ascend_to(path, top_path_level+1);
2848 skip_initializers();
2849 DEL_ARR_F(initializers);
2850 ascend_to(path, top_path_level+1);
2855 * Parses an initializer. Parsers either a compound literal
2856 * (env->declaration == NULL) or an initializer of a declaration.
2858 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2860 type_t *type = skip_typeref(env->type);
2861 initializer_t *result = NULL;
2864 if (is_type_scalar(type)) {
2865 result = parse_scalar_initializer(type, env->must_be_constant);
2866 } else if (token.type == '{') {
2870 memset(&path, 0, sizeof(path));
2871 path.top_type = env->type;
2872 path.path = NEW_ARR_F(type_path_entry_t, 0);
2874 descend_into_subtype(&path);
2876 add_anchor_token('}');
2877 result = parse_sub_initializer(&path, env->type, 1, env);
2878 rem_anchor_token('}');
2880 max_index = path.max_index;
2881 DEL_ARR_F(path.path);
2885 /* parse_scalar_initializer() also works in this case: we simply
2886 * have an expression without {} around it */
2887 result = parse_scalar_initializer(type, env->must_be_constant);
2890 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2891 * the array type size */
2892 if (is_type_array(type) && type->array.size_expression == NULL
2893 && result != NULL) {
2895 switch (result->kind) {
2896 case INITIALIZER_LIST:
2897 size = max_index + 1;
2900 case INITIALIZER_STRING:
2901 size = result->string.string.size;
2904 case INITIALIZER_WIDE_STRING:
2905 size = result->wide_string.string.size;
2908 case INITIALIZER_DESIGNATOR:
2909 case INITIALIZER_VALUE:
2910 /* can happen for parse errors */
2915 internal_errorf(HERE, "invalid initializer type");
2918 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2919 cnst->base.type = type_size_t;
2920 cnst->conste.v.int_value = size;
2922 type_t *new_type = duplicate_type(type);
2924 new_type->array.size_expression = cnst;
2925 new_type->array.size_constant = true;
2926 new_type->array.has_implicit_size = true;
2927 new_type->array.size = size;
2928 env->type = new_type;
2936 static void append_entity(scope_t *scope, entity_t *entity)
2938 if (scope->last_entity != NULL) {
2939 scope->last_entity->base.next = entity;
2941 scope->entities = entity;
2943 scope->last_entity = entity;
2947 static compound_t *parse_compound_type_specifier(bool is_struct)
2949 gnu_attribute_t *attributes = NULL;
2950 decl_modifiers_t modifiers = 0;
2957 symbol_t *symbol = NULL;
2958 compound_t *compound = NULL;
2960 if (token.type == T___attribute__) {
2961 modifiers |= parse_attributes(&attributes);
2964 if (token.type == T_IDENTIFIER) {
2965 symbol = token.v.symbol;
2968 namespace_tag_t const namespc =
2969 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2970 entity_t *entity = get_entity(symbol, namespc);
2971 if (entity != NULL) {
2972 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2973 compound = &entity->compound;
2974 if (compound->base.parent_scope != current_scope &&
2975 (token.type == '{' || token.type == ';')) {
2976 /* we're in an inner scope and have a definition. Override
2977 existing definition in outer scope */
2979 } else if (compound->complete && token.type == '{') {
2980 assert(symbol != NULL);
2981 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2982 is_struct ? "struct" : "union", symbol,
2983 &compound->base.source_position);
2984 /* clear members in the hope to avoid further errors */
2985 compound->members.entities = NULL;
2988 } else if (token.type != '{') {
2990 parse_error_expected("while parsing struct type specifier",
2991 T_IDENTIFIER, '{', NULL);
2993 parse_error_expected("while parsing union type specifier",
2994 T_IDENTIFIER, '{', NULL);
3000 if (compound == NULL) {
3001 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3002 entity_t *entity = allocate_entity_zero(kind);
3003 compound = &entity->compound;
3005 compound->base.namespc =
3006 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3007 compound->base.source_position = token.source_position;
3008 compound->base.symbol = symbol;
3009 compound->base.parent_scope = current_scope;
3010 if (symbol != NULL) {
3011 environment_push(entity);
3013 append_entity(current_scope, entity);
3016 if (token.type == '{') {
3017 parse_compound_type_entries(compound);
3018 modifiers |= parse_attributes(&attributes);
3020 if (symbol == NULL) {
3021 assert(anonymous_entity == NULL);
3022 anonymous_entity = (entity_t*)compound;
3026 compound->modifiers |= modifiers;
3030 static void parse_enum_entries(type_t *const enum_type)
3034 if (token.type == '}') {
3035 errorf(HERE, "empty enum not allowed");
3040 add_anchor_token('}');
3042 if (token.type != T_IDENTIFIER) {
3043 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3045 rem_anchor_token('}');
3049 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3050 entity->enum_value.enum_type = enum_type;
3051 entity->base.symbol = token.v.symbol;
3052 entity->base.source_position = token.source_position;
3055 if (token.type == '=') {
3057 expression_t *value = parse_constant_expression();
3059 value = create_implicit_cast(value, enum_type);
3060 entity->enum_value.value = value;
3065 record_entity(entity, false);
3067 if (token.type != ',')
3070 } while (token.type != '}');
3071 rem_anchor_token('}');
3079 static type_t *parse_enum_specifier(void)
3081 gnu_attribute_t *attributes = NULL;
3086 if (token.type == T_IDENTIFIER) {
3087 symbol = token.v.symbol;
3090 entity = get_entity(symbol, NAMESPACE_ENUM);
3091 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3092 } else if (token.type != '{') {
3093 parse_error_expected("while parsing enum type specifier",
3094 T_IDENTIFIER, '{', NULL);
3101 if (entity == NULL) {
3102 entity = allocate_entity_zero(ENTITY_ENUM);
3103 entity->base.namespc = NAMESPACE_ENUM;
3104 entity->base.source_position = token.source_position;
3105 entity->base.symbol = symbol;
3106 entity->base.parent_scope = current_scope;
3109 type_t *const type = allocate_type_zero(TYPE_ENUM);
3110 type->enumt.enume = &entity->enume;
3112 if (token.type == '{') {
3113 if (entity->enume.complete) {
3114 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3115 symbol, &entity->base.source_position);
3117 if (symbol != NULL) {
3118 environment_push(entity);
3120 append_entity(current_scope, entity);
3121 entity->enume.complete = true;
3123 parse_enum_entries(type);
3124 parse_attributes(&attributes);
3126 if (symbol == NULL) {
3127 assert(anonymous_entity == NULL);
3128 anonymous_entity = entity;
3130 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3131 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3139 * if a symbol is a typedef to another type, return true
3141 static bool is_typedef_symbol(symbol_t *symbol)
3143 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3144 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3147 static type_t *parse_typeof(void)
3154 add_anchor_token(')');
3156 expression_t *expression = NULL;
3158 bool old_type_prop = in_type_prop;
3159 bool old_gcc_extension = in_gcc_extension;
3160 in_type_prop = true;
3162 while (token.type == T___extension__) {
3163 /* This can be a prefix to a typename or an expression. */
3165 in_gcc_extension = true;
3167 switch (token.type) {
3169 if (is_typedef_symbol(token.v.symbol)) {
3170 type = parse_typename();
3172 expression = parse_expression();
3173 type = expression->base.type;
3178 type = parse_typename();
3182 expression = parse_expression();
3183 type = expression->base.type;
3186 in_type_prop = old_type_prop;
3187 in_gcc_extension = old_gcc_extension;
3189 rem_anchor_token(')');
3192 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3193 typeof_type->typeoft.expression = expression;
3194 typeof_type->typeoft.typeof_type = type;
3201 typedef enum specifiers_t {
3202 SPECIFIER_SIGNED = 1 << 0,
3203 SPECIFIER_UNSIGNED = 1 << 1,
3204 SPECIFIER_LONG = 1 << 2,
3205 SPECIFIER_INT = 1 << 3,
3206 SPECIFIER_DOUBLE = 1 << 4,
3207 SPECIFIER_CHAR = 1 << 5,
3208 SPECIFIER_SHORT = 1 << 6,
3209 SPECIFIER_LONG_LONG = 1 << 7,
3210 SPECIFIER_FLOAT = 1 << 8,
3211 SPECIFIER_BOOL = 1 << 9,
3212 SPECIFIER_VOID = 1 << 10,
3213 SPECIFIER_INT8 = 1 << 11,
3214 SPECIFIER_INT16 = 1 << 12,
3215 SPECIFIER_INT32 = 1 << 13,
3216 SPECIFIER_INT64 = 1 << 14,
3217 SPECIFIER_INT128 = 1 << 15,
3218 SPECIFIER_COMPLEX = 1 << 16,
3219 SPECIFIER_IMAGINARY = 1 << 17,
3222 static type_t *create_builtin_type(symbol_t *const symbol,
3223 type_t *const real_type)
3225 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3226 type->builtin.symbol = symbol;
3227 type->builtin.real_type = real_type;
3229 type_t *result = typehash_insert(type);
3230 if (type != result) {
3237 static type_t *get_typedef_type(symbol_t *symbol)
3239 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3240 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3243 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3244 type->typedeft.typedefe = &entity->typedefe;
3250 * check for the allowed MS alignment values.
3252 static bool check_alignment_value(long long intvalue)
3254 if (intvalue < 1 || intvalue > 8192) {
3255 errorf(HERE, "illegal alignment value");
3258 unsigned v = (unsigned)intvalue;
3259 for (unsigned i = 1; i <= 8192; i += i) {
3263 errorf(HERE, "alignment must be power of two");
3267 #define DET_MOD(name, tag) do { \
3268 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3269 *modifiers |= tag; \
3272 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3274 decl_modifiers_t *modifiers = &specifiers->modifiers;
3277 if (token.type == T_restrict) {
3279 DET_MOD(restrict, DM_RESTRICT);
3281 } else if (token.type != T_IDENTIFIER)
3283 symbol_t *symbol = token.v.symbol;
3284 if (symbol == sym_align) {
3287 if (token.type != T_INTEGER)
3289 if (check_alignment_value(token.v.intvalue)) {
3290 if (specifiers->alignment != 0 && warning.other)
3291 warningf(HERE, "align used more than once");
3292 specifiers->alignment = (unsigned char)token.v.intvalue;
3296 } else if (symbol == sym_allocate) {
3299 if (token.type != T_IDENTIFIER)
3301 (void)token.v.symbol;
3303 } else if (symbol == sym_dllimport) {
3305 DET_MOD(dllimport, DM_DLLIMPORT);
3306 } else if (symbol == sym_dllexport) {
3308 DET_MOD(dllexport, DM_DLLEXPORT);
3309 } else if (symbol == sym_thread) {
3311 DET_MOD(thread, DM_THREAD);
3312 } else if (symbol == sym_naked) {
3314 DET_MOD(naked, DM_NAKED);
3315 } else if (symbol == sym_noinline) {
3317 DET_MOD(noinline, DM_NOINLINE);
3318 } else if (symbol == sym_noreturn) {
3320 DET_MOD(noreturn, DM_NORETURN);
3321 } else if (symbol == sym_nothrow) {
3323 DET_MOD(nothrow, DM_NOTHROW);
3324 } else if (symbol == sym_novtable) {
3326 DET_MOD(novtable, DM_NOVTABLE);
3327 } else if (symbol == sym_property) {
3331 bool is_get = false;
3332 if (token.type != T_IDENTIFIER)
3334 if (token.v.symbol == sym_get) {
3336 } else if (token.v.symbol == sym_put) {
3338 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3343 if (token.type != T_IDENTIFIER)
3346 if (specifiers->get_property_sym != NULL) {
3347 errorf(HERE, "get property name already specified");
3349 specifiers->get_property_sym = token.v.symbol;
3352 if (specifiers->put_property_sym != NULL) {
3353 errorf(HERE, "put property name already specified");
3355 specifiers->put_property_sym = token.v.symbol;
3359 if (token.type == ',') {
3366 } else if (symbol == sym_selectany) {
3368 DET_MOD(selectany, DM_SELECTANY);
3369 } else if (symbol == sym_uuid) {
3372 if (token.type != T_STRING_LITERAL)
3376 } else if (symbol == sym_deprecated) {
3378 if (specifiers->deprecated != 0 && warning.other)
3379 warningf(HERE, "deprecated used more than once");
3380 specifiers->deprecated = true;
3381 if (token.type == '(') {
3383 if (token.type == T_STRING_LITERAL) {
3384 specifiers->deprecated_string = token.v.string.begin;
3387 errorf(HERE, "string literal expected");
3391 } else if (symbol == sym_noalias) {
3393 DET_MOD(noalias, DM_NOALIAS);
3396 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3398 if (token.type == '(')
3402 if (token.type == ',')
3409 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3411 entity_t *entity = allocate_entity_zero(kind);
3412 entity->base.source_position = *HERE;
3413 entity->base.symbol = symbol;
3414 if (is_declaration(entity)) {
3415 entity->declaration.type = type_error_type;
3416 entity->declaration.implicit = true;
3417 } else if (kind == ENTITY_TYPEDEF) {
3418 entity->typedefe.type = type_error_type;
3420 record_entity(entity, false);
3424 static void parse_microsoft_based(based_spec_t *based_spec)
3426 if (token.type != T_IDENTIFIER) {
3427 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3430 symbol_t *symbol = token.v.symbol;
3431 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3433 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3434 errorf(HERE, "'%Y' is not a variable name.", symbol);
3435 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3437 variable_t *variable = &entity->variable;
3439 if (based_spec->base_variable != NULL) {
3440 errorf(HERE, "__based type qualifier specified more than once");
3442 based_spec->source_position = token.source_position;
3443 based_spec->base_variable = variable;
3445 type_t *const type = variable->base.type;
3447 if (is_type_valid(type)) {
3448 if (! is_type_pointer(skip_typeref(type))) {
3449 errorf(HERE, "variable in __based modifier must have pointer type instead of %T", type);
3451 if (variable->base.base.parent_scope != file_scope) {
3452 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3460 * Finish the construction of a struct type by calculating
3461 * its size, offsets, alignment.
3463 static void finish_struct_type(compound_type_t *type)
3465 assert(type->compound != NULL);
3467 compound_t *compound = type->compound;
3468 if (!compound->complete)
3473 il_alignment_t alignment = 1;
3474 bool need_pad = false;
3476 entity_t *entry = compound->members.entities;
3477 for (; entry != NULL; entry = entry->base.next) {
3478 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3481 type_t *m_type = skip_typeref(entry->declaration.type);
3482 if (! is_type_valid(m_type)) {
3483 /* simply ignore errors here */
3486 il_alignment_t m_alignment = m_type->base.alignment;
3487 if (m_alignment > alignment)
3488 alignment = m_alignment;
3490 offset = (size + m_alignment - 1) & -m_alignment;
3494 entry->compound_member.offset = offset;
3495 size = offset + m_type->base.size;
3497 if (type->base.alignment != 0) {
3498 alignment = type->base.alignment;
3501 offset = (size + alignment - 1) & -alignment;
3505 if (warning.padded && need_pad) {
3506 warningf(&compound->base.source_position,
3507 "'%#T' needs padding", type, compound->base.symbol);
3509 if (warning.packed && !need_pad) {
3510 warningf(&compound->base.source_position,
3511 "superfluous packed attribute on '%#T'",
3512 type, compound->base.symbol);
3515 type->base.size = offset;
3516 type->base.alignment = alignment;
3520 * Finish the construction of an union type by calculating
3521 * its size and alignment.
3523 static void finish_union_type(compound_type_t *type)
3525 assert(type->compound != NULL);
3527 compound_t *compound = type->compound;
3528 if (! compound->complete)
3532 il_alignment_t alignment = 1;
3534 entity_t *entry = compound->members.entities;
3535 for (; entry != NULL; entry = entry->base.next) {
3536 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3539 type_t *m_type = skip_typeref(entry->declaration.type);
3540 if (! is_type_valid(m_type))
3543 entry->compound_member.offset = 0;
3544 if (m_type->base.size > size)
3545 size = m_type->base.size;
3546 if (m_type->base.alignment > alignment)
3547 alignment = m_type->base.alignment;
3549 if (type->base.alignment != 0) {
3550 alignment = type->base.alignment;
3552 size = (size + alignment - 1) & -alignment;
3553 type->base.size = size;
3554 type->base.alignment = alignment;
3557 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3559 type_t *type = NULL;
3560 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3561 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3562 unsigned type_specifiers = 0;
3563 bool newtype = false;
3564 bool saw_error = false;
3565 bool old_gcc_extension = in_gcc_extension;
3567 specifiers->source_position = token.source_position;
3570 specifiers->modifiers
3571 |= parse_attributes(&specifiers->gnu_attributes);
3572 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3573 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3575 switch (token.type) {
3578 #define MATCH_STORAGE_CLASS(token, class) \
3580 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3581 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3583 specifiers->storage_class = class; \
3587 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3588 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3589 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3590 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3591 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3596 add_anchor_token(')');
3597 parse_microsoft_extended_decl_modifier(specifiers);
3598 rem_anchor_token(')');
3603 switch (specifiers->storage_class) {
3604 case STORAGE_CLASS_NONE:
3605 specifiers->storage_class = STORAGE_CLASS_THREAD;
3608 case STORAGE_CLASS_EXTERN:
3609 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3612 case STORAGE_CLASS_STATIC:
3613 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3617 errorf(HERE, "multiple storage classes in declaration specifiers");
3623 /* type qualifiers */
3624 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3626 qualifiers |= qualifier; \
3630 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3631 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3632 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3633 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3634 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3635 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3636 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3637 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3639 case T___extension__:
3641 in_gcc_extension = true;
3644 /* type specifiers */
3645 #define MATCH_SPECIFIER(token, specifier, name) \
3647 if (type_specifiers & specifier) { \
3648 errorf(HERE, "multiple " name " type specifiers given"); \
3650 type_specifiers |= specifier; \
3655 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3656 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3657 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3658 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3659 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3660 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3661 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3662 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3663 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3664 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3665 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3666 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3667 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3668 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3669 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3670 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3671 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3673 case T__forceinline:
3674 /* only in microsoft mode */
3675 specifiers->modifiers |= DM_FORCEINLINE;
3680 specifiers->is_inline = true;
3684 if (type_specifiers & SPECIFIER_LONG_LONG) {
3685 errorf(HERE, "multiple type specifiers given");
3686 } else if (type_specifiers & SPECIFIER_LONG) {
3687 type_specifiers |= SPECIFIER_LONG_LONG;
3689 type_specifiers |= SPECIFIER_LONG;
3695 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3697 type->compound.compound = parse_compound_type_specifier(true);
3698 finish_struct_type(&type->compound);
3702 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3703 type->compound.compound = parse_compound_type_specifier(false);
3704 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3705 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3706 finish_union_type(&type->compound);
3710 type = parse_enum_specifier();
3713 type = parse_typeof();
3715 case T___builtin_va_list:
3716 type = duplicate_type(type_valist);
3720 case T_IDENTIFIER: {
3721 /* only parse identifier if we haven't found a type yet */
3722 if (type != NULL || type_specifiers != 0) {
3723 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3724 * declaration, so it doesn't generate errors about expecting '(' or
3726 switch (look_ahead(1)->type) {
3733 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3737 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3742 goto finish_specifiers;
3746 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3747 if (typedef_type == NULL) {
3748 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3749 * declaration, so it doesn't generate 'implicit int' followed by more
3750 * errors later on. */
3751 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3757 errorf(HERE, "%K does not name a type", &token);
3760 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3762 type = allocate_type_zero(TYPE_TYPEDEF);
3763 type->typedeft.typedefe = &entity->typedefe;
3767 if (la1_type == '&' || la1_type == '*')
3768 goto finish_specifiers;
3773 goto finish_specifiers;
3778 type = typedef_type;
3782 /* function specifier */
3784 goto finish_specifiers;
3789 in_gcc_extension = old_gcc_extension;
3791 if (type == NULL || (saw_error && type_specifiers != 0)) {
3792 atomic_type_kind_t atomic_type;
3794 /* match valid basic types */
3795 switch (type_specifiers) {
3796 case SPECIFIER_VOID:
3797 atomic_type = ATOMIC_TYPE_VOID;
3799 case SPECIFIER_CHAR:
3800 atomic_type = ATOMIC_TYPE_CHAR;
3802 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3803 atomic_type = ATOMIC_TYPE_SCHAR;
3805 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3806 atomic_type = ATOMIC_TYPE_UCHAR;
3808 case SPECIFIER_SHORT:
3809 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3810 case SPECIFIER_SHORT | SPECIFIER_INT:
3811 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3812 atomic_type = ATOMIC_TYPE_SHORT;
3814 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3815 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3816 atomic_type = ATOMIC_TYPE_USHORT;
3819 case SPECIFIER_SIGNED:
3820 case SPECIFIER_SIGNED | SPECIFIER_INT:
3821 atomic_type = ATOMIC_TYPE_INT;
3823 case SPECIFIER_UNSIGNED:
3824 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3825 atomic_type = ATOMIC_TYPE_UINT;
3827 case SPECIFIER_LONG:
3828 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3829 case SPECIFIER_LONG | SPECIFIER_INT:
3830 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3831 atomic_type = ATOMIC_TYPE_LONG;
3833 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3834 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3835 atomic_type = ATOMIC_TYPE_ULONG;
3838 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3839 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3840 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3841 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3843 atomic_type = ATOMIC_TYPE_LONGLONG;
3844 goto warn_about_long_long;
3846 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3847 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3849 atomic_type = ATOMIC_TYPE_ULONGLONG;
3850 warn_about_long_long:
3851 if (warning.long_long) {
3852 warningf(&specifiers->source_position,
3853 "ISO C90 does not support 'long long'");
3857 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3858 atomic_type = unsigned_int8_type_kind;
3861 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3862 atomic_type = unsigned_int16_type_kind;
3865 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3866 atomic_type = unsigned_int32_type_kind;
3869 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3870 atomic_type = unsigned_int64_type_kind;
3873 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3874 atomic_type = unsigned_int128_type_kind;
3877 case SPECIFIER_INT8:
3878 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3879 atomic_type = int8_type_kind;
3882 case SPECIFIER_INT16:
3883 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3884 atomic_type = int16_type_kind;
3887 case SPECIFIER_INT32:
3888 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3889 atomic_type = int32_type_kind;
3892 case SPECIFIER_INT64:
3893 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3894 atomic_type = int64_type_kind;
3897 case SPECIFIER_INT128:
3898 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3899 atomic_type = int128_type_kind;
3902 case SPECIFIER_FLOAT:
3903 atomic_type = ATOMIC_TYPE_FLOAT;
3905 case SPECIFIER_DOUBLE:
3906 atomic_type = ATOMIC_TYPE_DOUBLE;
3908 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3909 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3911 case SPECIFIER_BOOL:
3912 atomic_type = ATOMIC_TYPE_BOOL;
3914 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3915 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3916 atomic_type = ATOMIC_TYPE_FLOAT;
3918 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3919 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3920 atomic_type = ATOMIC_TYPE_DOUBLE;
3922 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3923 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3924 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3927 /* invalid specifier combination, give an error message */
3928 if (type_specifiers == 0) {
3932 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3933 if (!(c_mode & _CXX) && !strict_mode) {
3934 if (warning.implicit_int) {
3935 warningf(HERE, "no type specifiers in declaration, using 'int'");
3937 atomic_type = ATOMIC_TYPE_INT;
3940 errorf(HERE, "no type specifiers given in declaration");
3942 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3943 (type_specifiers & SPECIFIER_UNSIGNED)) {
3944 errorf(HERE, "signed and unsigned specifiers given");
3945 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3946 errorf(HERE, "only integer types can be signed or unsigned");
3948 errorf(HERE, "multiple datatypes in declaration");
3953 if (type_specifiers & SPECIFIER_COMPLEX) {
3954 type = allocate_type_zero(TYPE_COMPLEX);
3955 type->complex.akind = atomic_type;
3956 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3957 type = allocate_type_zero(TYPE_IMAGINARY);
3958 type->imaginary.akind = atomic_type;
3960 type = allocate_type_zero(TYPE_ATOMIC);
3961 type->atomic.akind = atomic_type;
3964 } else if (type_specifiers != 0) {
3965 errorf(HERE, "multiple datatypes in declaration");
3968 /* FIXME: check type qualifiers here */
3970 type->base.qualifiers = qualifiers;
3971 type->base.modifiers = modifiers;
3973 type_t *result = typehash_insert(type);
3974 if (newtype && result != type) {
3978 specifiers->type = result;
3982 specifiers->type = type_error_type;
3986 static type_qualifiers_t parse_type_qualifiers(void)
3988 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3991 switch (token.type) {
3992 /* type qualifiers */
3993 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3994 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3995 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3996 /* microsoft extended type modifiers */
3997 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3998 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3999 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
4000 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
4001 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4010 * Parses an K&R identifier list
4012 static void parse_identifier_list(scope_t *scope)
4015 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4016 entity->base.source_position = token.source_position;
4017 entity->base.namespc = NAMESPACE_NORMAL;
4018 entity->base.symbol = token.v.symbol;
4019 /* a K&R parameter has no type, yet */
4022 append_entity(scope, entity);
4024 if (token.type != ',') {
4028 } while (token.type == T_IDENTIFIER);
4031 static type_t *automatic_type_conversion(type_t *orig_type);
4033 static void semantic_parameter(declaration_t *declaration)
4035 /* TODO: improve error messages */
4036 source_position_t const* const pos = &declaration->base.source_position;
4039 switch (declaration->declared_storage_class) {
4040 /* Allowed storage classes */
4041 case STORAGE_CLASS_NONE:
4042 case STORAGE_CLASS_REGISTER:
4046 errorf(pos, "parameter may only have none or register storage class");
4050 type_t *const orig_type = declaration->type;
4051 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4052 * sugar. Turn it into a pointer.
4053 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4054 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4056 type_t *const type = automatic_type_conversion(orig_type);
4057 declaration->type = type;
4059 if (is_type_incomplete(skip_typeref(type))) {
4060 errorf(pos, "parameter '%#T' is of incomplete type",
4061 orig_type, declaration->base.symbol);
4065 static entity_t *parse_parameter(void)
4067 declaration_specifiers_t specifiers;
4068 memset(&specifiers, 0, sizeof(specifiers));
4070 parse_declaration_specifiers(&specifiers);
4072 entity_t *entity = parse_declarator(&specifiers, true, false);
4073 anonymous_entity = NULL;
4078 * Parses function type parameters (and optionally creates variable_t entities
4079 * for them in a scope)
4081 static void parse_parameters(function_type_t *type, scope_t *scope)
4084 add_anchor_token(')');
4085 int saved_comma_state = save_and_reset_anchor_state(',');
4087 if (token.type == T_IDENTIFIER &&
4088 !is_typedef_symbol(token.v.symbol)) {
4089 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4090 if (la1_type == ',' || la1_type == ')') {
4091 type->kr_style_parameters = true;
4092 parse_identifier_list(scope);
4093 goto parameters_finished;
4097 if (token.type == ')') {
4098 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4099 if (!(c_mode & _CXX))
4100 type->unspecified_parameters = true;
4101 goto parameters_finished;
4104 function_parameter_t *parameter;
4105 function_parameter_t *last_parameter = NULL;
4108 switch (token.type) {
4111 type->variadic = true;
4112 goto parameters_finished;
4115 case T___extension__:
4118 entity_t *entity = parse_parameter();
4119 if (entity->kind == ENTITY_TYPEDEF) {
4120 errorf(&entity->base.source_position,
4121 "typedef not allowed as function parameter");
4124 assert(is_declaration(entity));
4126 /* func(void) is not a parameter */
4127 if (last_parameter == NULL
4128 && token.type == ')'
4129 && entity->base.symbol == NULL
4130 && skip_typeref(entity->declaration.type) == type_void) {
4131 goto parameters_finished;
4133 semantic_parameter(&entity->declaration);
4135 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4136 memset(parameter, 0, sizeof(parameter[0]));
4137 parameter->type = entity->declaration.type;
4139 if (scope != NULL) {
4140 append_entity(scope, entity);
4143 if (last_parameter != NULL) {
4144 last_parameter->next = parameter;
4146 type->parameters = parameter;
4148 last_parameter = parameter;
4153 goto parameters_finished;
4155 if (token.type != ',') {
4156 goto parameters_finished;
4162 parameters_finished:
4163 rem_anchor_token(')');
4167 restore_anchor_state(',', saved_comma_state);
4170 typedef enum construct_type_kind_t {
4173 CONSTRUCT_REFERENCE,
4176 } construct_type_kind_t;
4178 typedef struct construct_type_t construct_type_t;
4179 struct construct_type_t {
4180 construct_type_kind_t kind;
4181 construct_type_t *next;
4184 typedef struct parsed_pointer_t parsed_pointer_t;
4185 struct parsed_pointer_t {
4186 construct_type_t construct_type;
4187 type_qualifiers_t type_qualifiers;
4188 variable_t *base_variable; /**< MS __based extension. */
4191 typedef struct parsed_reference_t parsed_reference_t;
4192 struct parsed_reference_t {
4193 construct_type_t construct_type;
4196 typedef struct construct_function_type_t construct_function_type_t;
4197 struct construct_function_type_t {
4198 construct_type_t construct_type;
4199 type_t *function_type;
4202 typedef struct parsed_array_t parsed_array_t;
4203 struct parsed_array_t {
4204 construct_type_t construct_type;
4205 type_qualifiers_t type_qualifiers;
4211 typedef struct construct_base_type_t construct_base_type_t;
4212 struct construct_base_type_t {
4213 construct_type_t construct_type;
4217 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4221 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4222 memset(pointer, 0, sizeof(pointer[0]));
4223 pointer->construct_type.kind = CONSTRUCT_POINTER;
4224 pointer->type_qualifiers = parse_type_qualifiers();
4225 pointer->base_variable = base_variable;
4227 return &pointer->construct_type;
4230 static construct_type_t *parse_reference_declarator(void)
4234 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4235 memset(reference, 0, sizeof(reference[0]));
4236 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4238 return (construct_type_t*)reference;
4241 static construct_type_t *parse_array_declarator(void)
4244 add_anchor_token(']');
4246 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4247 memset(array, 0, sizeof(array[0]));
4248 array->construct_type.kind = CONSTRUCT_ARRAY;
4250 if (token.type == T_static) {
4251 array->is_static = true;
4255 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4256 if (type_qualifiers != 0) {
4257 if (token.type == T_static) {
4258 array->is_static = true;
4262 array->type_qualifiers = type_qualifiers;
4264 if (token.type == '*' && look_ahead(1)->type == ']') {
4265 array->is_variable = true;
4267 } else if (token.type != ']') {
4268 array->size = parse_assignment_expression();
4271 rem_anchor_token(']');
4275 return &array->construct_type;
4278 static construct_type_t *parse_function_declarator(scope_t *scope,
4279 decl_modifiers_t modifiers)
4281 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4282 function_type_t *ftype = &type->function;
4284 ftype->linkage = current_linkage;
4286 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4287 case DM_NONE: break;
4288 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4289 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4290 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4291 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4294 errorf(HERE, "multiple calling conventions in declaration");
4298 parse_parameters(ftype, scope);
4300 construct_function_type_t *construct_function_type =
4301 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4302 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4303 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4304 construct_function_type->function_type = type;
4306 return &construct_function_type->construct_type;
4309 typedef struct parse_declarator_env_t {
4310 decl_modifiers_t modifiers;
4312 source_position_t source_position;
4314 } parse_declarator_env_t;
4316 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4317 bool may_be_abstract)
4319 /* construct a single linked list of construct_type_t's which describe
4320 * how to construct the final declarator type */
4321 construct_type_t *first = NULL;
4322 construct_type_t *last = NULL;
4323 gnu_attribute_t *attributes = NULL;
4325 decl_modifiers_t modifiers = parse_attributes(&attributes);
4327 /* MS __based extension */
4328 based_spec_t base_spec;
4329 base_spec.base_variable = NULL;
4332 construct_type_t *type;
4333 switch (token.type) {
4335 if (!(c_mode & _CXX))
4336 errorf(HERE, "references are only available for C++");
4337 if (base_spec.base_variable != NULL)
4338 warningf(&base_spec.source_position,
4339 "__based does not precede a pointer operator, ignored");
4340 type = parse_reference_declarator();
4342 base_spec.base_variable = NULL;
4346 type = parse_pointer_declarator(base_spec.base_variable);
4348 base_spec.base_variable = NULL;
4354 add_anchor_token(')');
4355 parse_microsoft_based(&base_spec);
4356 rem_anchor_token(')');
4361 goto ptr_operator_end;
4372 /* TODO: find out if this is correct */
4373 modifiers |= parse_attributes(&attributes);
4376 if (base_spec.base_variable != NULL)
4377 warningf(&base_spec.source_position,
4378 "__based does not precede a pointer operator, ignored");
4381 modifiers |= env->modifiers;
4382 env->modifiers = modifiers;
4385 construct_type_t *inner_types = NULL;
4387 switch (token.type) {
4390 errorf(HERE, "no identifier expected in typename");
4392 env->symbol = token.v.symbol;
4393 env->source_position = token.source_position;
4399 add_anchor_token(')');
4400 inner_types = parse_inner_declarator(env, may_be_abstract);
4401 if (inner_types != NULL) {
4402 /* All later declarators only modify the return type */
4405 rem_anchor_token(')');
4409 if (may_be_abstract)
4411 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4416 construct_type_t *p = last;
4419 construct_type_t *type;
4420 switch (token.type) {
4422 scope_t *scope = NULL;
4424 scope = &env->parameters;
4426 type = parse_function_declarator(scope, modifiers);
4430 type = parse_array_declarator();
4433 goto declarator_finished;
4436 /* insert in the middle of the list (behind p) */
4438 type->next = p->next;
4449 declarator_finished:
4450 /* append inner_types at the end of the list, we don't to set last anymore
4451 * as it's not needed anymore */
4453 assert(first == NULL);
4454 first = inner_types;
4456 last->next = inner_types;
4464 static void parse_declaration_attributes(entity_t *entity)
4466 gnu_attribute_t *attributes = NULL;
4467 decl_modifiers_t modifiers = parse_attributes(&attributes);
4473 if (entity->kind == ENTITY_TYPEDEF) {
4474 modifiers |= entity->typedefe.modifiers;
4475 type = entity->typedefe.type;
4477 assert(is_declaration(entity));
4478 modifiers |= entity->declaration.modifiers;
4479 type = entity->declaration.type;
4484 /* handle these strange/stupid mode attributes */
4485 gnu_attribute_t *attribute = attributes;
4486 for ( ; attribute != NULL; attribute = attribute->next) {
4487 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4490 atomic_type_kind_t akind = attribute->u.akind;
4491 if (!is_type_signed(type)) {
4493 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4494 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4495 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4496 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4498 panic("invalid akind in mode attribute");
4502 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4503 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4504 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4505 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4507 panic("invalid akind in mode attribute");
4511 type = make_atomic_type(akind, type->base.qualifiers);
4514 type_modifiers_t type_modifiers = type->base.modifiers;
4515 if (modifiers & DM_TRANSPARENT_UNION)
4516 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4518 if (type->base.modifiers != type_modifiers) {
4519 type_t *copy = duplicate_type(type);
4520 copy->base.modifiers = type_modifiers;
4522 type = typehash_insert(copy);
4524 obstack_free(type_obst, copy);
4528 if (entity->kind == ENTITY_TYPEDEF) {
4529 entity->typedefe.type = type;
4530 entity->typedefe.modifiers = modifiers;
4532 entity->declaration.type = type;
4533 entity->declaration.modifiers = modifiers;
4537 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4539 construct_type_t *iter = construct_list;
4540 for (; iter != NULL; iter = iter->next) {
4541 switch (iter->kind) {
4542 case CONSTRUCT_INVALID:
4543 internal_errorf(HERE, "invalid type construction found");
4544 case CONSTRUCT_FUNCTION: {
4545 construct_function_type_t *construct_function_type
4546 = (construct_function_type_t*) iter;
4548 type_t *function_type = construct_function_type->function_type;
4550 function_type->function.return_type = type;
4552 type_t *skipped_return_type = skip_typeref(type);
4554 if (is_type_function(skipped_return_type)) {
4555 errorf(HERE, "function returning function is not allowed");
4556 } else if (is_type_array(skipped_return_type)) {
4557 errorf(HERE, "function returning array is not allowed");
4559 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4561 "type qualifiers in return type of function type are meaningless");
4565 type = function_type;
4569 case CONSTRUCT_POINTER: {
4570 if (is_type_reference(skip_typeref(type)))
4571 errorf(HERE, "cannot declare a pointer to reference");
4573 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4574 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4578 case CONSTRUCT_REFERENCE:
4579 if (is_type_reference(skip_typeref(type)))
4580 errorf(HERE, "cannot declare a reference to reference");
4582 type = make_reference_type(type);
4585 case CONSTRUCT_ARRAY: {
4586 if (is_type_reference(skip_typeref(type)))
4587 errorf(HERE, "cannot declare an array of references");
4589 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4590 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4592 expression_t *size_expression = parsed_array->size;
4593 if (size_expression != NULL) {
4595 = create_implicit_cast(size_expression, type_size_t);
4598 array_type->base.qualifiers = parsed_array->type_qualifiers;
4599 array_type->array.element_type = type;
4600 array_type->array.is_static = parsed_array->is_static;
4601 array_type->array.is_variable = parsed_array->is_variable;
4602 array_type->array.size_expression = size_expression;
4604 if (size_expression != NULL) {
4605 if (is_constant_expression(size_expression)) {
4606 array_type->array.size_constant = true;
4607 array_type->array.size
4608 = fold_constant(size_expression);
4610 array_type->array.is_vla = true;
4614 type_t *skipped_type = skip_typeref(type);
4616 if (is_type_incomplete(skipped_type)) {
4617 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4618 } else if (is_type_function(skipped_type)) {
4619 errorf(HERE, "array of functions is not allowed");
4626 type_t *hashed_type = typehash_insert(type);
4627 if (hashed_type != type) {
4628 /* the function type was constructed earlier freeing it here will
4629 * destroy other types... */
4630 if (iter->kind != CONSTRUCT_FUNCTION) {
4640 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4641 bool may_be_abstract,
4642 bool create_compound_member)
4644 parse_declarator_env_t env;
4645 memset(&env, 0, sizeof(env));
4646 env.modifiers = specifiers->modifiers;
4648 construct_type_t *construct_type
4649 = parse_inner_declarator(&env, may_be_abstract);
4650 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4652 if (construct_type != NULL) {
4653 obstack_free(&temp_obst, construct_type);
4657 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4658 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4659 entity->base.symbol = env.symbol;
4660 entity->base.source_position = env.source_position;
4661 entity->typedefe.type = type;
4663 if (anonymous_entity != NULL) {
4664 if (is_type_compound(type)) {
4665 assert(anonymous_entity->compound.alias == NULL);
4666 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4667 anonymous_entity->kind == ENTITY_UNION);
4668 anonymous_entity->compound.alias = entity;
4669 anonymous_entity = NULL;
4670 } else if (is_type_enum(type)) {
4671 assert(anonymous_entity->enume.alias == NULL);
4672 assert(anonymous_entity->kind == ENTITY_ENUM);
4673 anonymous_entity->enume.alias = entity;
4674 anonymous_entity = NULL;
4678 if (create_compound_member) {
4679 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4680 } else if (is_type_function(skip_typeref(type))) {
4681 entity = allocate_entity_zero(ENTITY_FUNCTION);
4683 entity->function.is_inline = specifiers->is_inline;
4684 entity->function.parameters = env.parameters;
4686 entity = allocate_entity_zero(ENTITY_VARIABLE);
4688 entity->variable.get_property_sym = specifiers->get_property_sym;
4689 entity->variable.put_property_sym = specifiers->put_property_sym;
4690 if (specifiers->alignment != 0) {
4691 /* TODO: add checks here */
4692 entity->variable.alignment = specifiers->alignment;
4695 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4696 warningf(&env.source_position,
4697 "variable '%Y' declared 'inline'\n", env.symbol);
4701 entity->base.source_position = env.source_position;
4702 entity->base.symbol = env.symbol;
4703 entity->base.namespc = NAMESPACE_NORMAL;
4704 entity->declaration.type = type;
4705 entity->declaration.modifiers = env.modifiers;
4706 entity->declaration.deprecated_string = specifiers->deprecated_string;
4708 storage_class_t storage_class = specifiers->storage_class;
4709 entity->declaration.declared_storage_class = storage_class;
4711 if (storage_class == STORAGE_CLASS_NONE
4712 && current_scope != file_scope) {
4713 storage_class = STORAGE_CLASS_AUTO;
4715 entity->declaration.storage_class = storage_class;
4718 parse_declaration_attributes(entity);
4723 static type_t *parse_abstract_declarator(type_t *base_type)
4725 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4727 type_t *result = construct_declarator_type(construct_type, base_type);
4728 if (construct_type != NULL) {
4729 obstack_free(&temp_obst, construct_type);
4736 * Check if the declaration of main is suspicious. main should be a
4737 * function with external linkage, returning int, taking either zero
4738 * arguments, two, or three arguments of appropriate types, ie.
4740 * int main([ int argc, char **argv [, char **env ] ]).
4742 * @param decl the declaration to check
4743 * @param type the function type of the declaration
4745 static void check_type_of_main(const entity_t *entity)
4747 const source_position_t *pos = &entity->base.source_position;
4748 if (entity->kind != ENTITY_FUNCTION) {
4749 warningf(pos, "'main' is not a function");
4753 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4754 warningf(pos, "'main' is normally a non-static function");
4757 type_t *type = skip_typeref(entity->declaration.type);
4758 assert(is_type_function(type));
4760 function_type_t *func_type = &type->function;
4761 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4762 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4763 func_type->return_type);
4765 const function_parameter_t *parm = func_type->parameters;
4767 type_t *const first_type = parm->type;
4768 if (!types_compatible(skip_typeref(first_type), type_int)) {
4770 "first argument of 'main' should be 'int', but is '%T'",
4775 type_t *const second_type = parm->type;
4776 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4777 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4781 type_t *const third_type = parm->type;
4782 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4783 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4787 goto warn_arg_count;
4791 warningf(pos, "'main' takes only zero, two or three arguments");
4797 * Check if a symbol is the equal to "main".
4799 static bool is_sym_main(const symbol_t *const sym)
4801 return strcmp(sym->string, "main") == 0;
4804 static const char *get_entity_kind_name(entity_kind_t kind)
4806 switch ((entity_kind_tag_t) kind) {
4807 case ENTITY_FUNCTION: return "function";
4808 case ENTITY_VARIABLE: return "variable";
4809 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4810 case ENTITY_STRUCT: return "struct";
4811 case ENTITY_UNION: return "union";
4812 case ENTITY_ENUM: return "enum";
4813 case ENTITY_ENUM_VALUE: return "enum value";
4814 case ENTITY_LABEL: return "label";
4815 case ENTITY_LOCAL_LABEL: return "local label";
4816 case ENTITY_TYPEDEF: return "typedef";
4817 case ENTITY_NAMESPACE: return "namespace";
4818 case ENTITY_INVALID: break;
4821 panic("Invalid entity kind encountered in get_entity_kind_name");
4824 static void error_redefined_as_different_kind(const source_position_t *pos,
4825 const entity_t *old, entity_kind_t new_kind)
4827 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4828 get_entity_kind_name(old->kind), old->base.symbol,
4829 get_entity_kind_name(new_kind), &old->base.source_position);
4833 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4834 * for various problems that occur for multiple definitions
4836 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4838 const symbol_t *const symbol = entity->base.symbol;
4839 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4840 const source_position_t *pos = &entity->base.source_position;
4842 assert(symbol != NULL);
4843 entity_t *previous_entity = get_entity(symbol, namespc);
4844 /* pushing the same entity twice will break the stack structure */
4845 assert(previous_entity != entity);
4847 if (entity->kind == ENTITY_FUNCTION) {
4848 type_t *const orig_type = entity->declaration.type;
4849 type_t *const type = skip_typeref(orig_type);
4851 assert(is_type_function(type));
4852 if (type->function.unspecified_parameters &&
4853 warning.strict_prototypes &&
4854 previous_entity == NULL) {
4855 warningf(pos, "function declaration '%#T' is not a prototype",
4859 if (warning.main && current_scope == file_scope
4860 && is_sym_main(symbol)) {
4861 check_type_of_main(entity);
4865 if (is_declaration(entity)) {
4866 if (warning.nested_externs
4867 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4868 && current_scope != file_scope) {
4869 warningf(pos, "nested extern declaration of '%#T'",
4870 entity->declaration.type, symbol);
4874 if (previous_entity != NULL
4875 && previous_entity->base.parent_scope == ¤t_function->parameters
4876 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4878 assert(previous_entity->kind == ENTITY_VARIABLE);
4880 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4881 entity->declaration.type, symbol,
4882 previous_entity->declaration.type, symbol,
4883 &previous_entity->base.source_position);
4887 if (previous_entity != NULL
4888 && previous_entity->base.parent_scope == current_scope) {
4890 if (previous_entity->kind != entity->kind) {
4891 error_redefined_as_different_kind(pos, previous_entity,
4895 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4897 "redeclaration of enum entry '%Y' (declared %P)",
4898 symbol, &previous_entity->base.source_position);
4901 if (previous_entity->kind == ENTITY_TYPEDEF) {
4902 /* TODO: C++ allows this for exactly the same type */
4904 "redefinition of typedef '%Y' (declared %P)",
4905 symbol, &previous_entity->base.source_position);
4909 /* at this point we should have only VARIABLES or FUNCTIONS */
4910 assert(is_declaration(previous_entity) && is_declaration(entity));
4912 /* can happen for K&R style declarations */
4913 if (previous_entity->kind == ENTITY_VARIABLE
4914 && previous_entity->declaration.type == NULL
4915 && entity->kind == ENTITY_VARIABLE) {
4916 previous_entity->declaration.type = entity->declaration.type;
4917 previous_entity->declaration.storage_class
4918 = entity->declaration.storage_class;
4919 previous_entity->declaration.declared_storage_class
4920 = entity->declaration.declared_storage_class;
4921 previous_entity->declaration.modifiers
4922 = entity->declaration.modifiers;
4923 previous_entity->declaration.deprecated_string
4924 = entity->declaration.deprecated_string;
4926 assert(entity->declaration.type != NULL);
4928 declaration_t *const previous_declaration
4929 = &previous_entity->declaration;
4930 declaration_t *const declaration = &entity->declaration;
4931 type_t *const orig_type = entity->declaration.type;
4932 type_t *const type = skip_typeref(orig_type);
4934 type_t *prev_type = skip_typeref(previous_declaration->type);
4936 if (!types_compatible(type, prev_type)) {
4938 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4939 orig_type, symbol, previous_declaration->type, symbol,
4940 &previous_entity->base.source_position);
4942 unsigned old_storage_class = previous_declaration->storage_class;
4943 if (warning.redundant_decls && is_definition
4944 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4945 && !(previous_declaration->modifiers & DM_USED)
4946 && !previous_declaration->used) {
4947 warningf(&previous_entity->base.source_position,
4948 "unnecessary static forward declaration for '%#T'",
4949 previous_declaration->type, symbol);
4952 unsigned new_storage_class = declaration->storage_class;
4953 if (is_type_incomplete(prev_type)) {
4954 previous_declaration->type = type;
4958 /* pretend no storage class means extern for function
4959 * declarations (except if the previous declaration is neither
4960 * none nor extern) */
4961 if (entity->kind == ENTITY_FUNCTION) {
4962 if (prev_type->function.unspecified_parameters) {
4963 previous_declaration->type = type;
4967 switch (old_storage_class) {
4968 case STORAGE_CLASS_NONE:
4969 old_storage_class = STORAGE_CLASS_EXTERN;
4972 case STORAGE_CLASS_EXTERN:
4973 if (is_definition) {
4974 if (warning.missing_prototypes &&
4975 prev_type->function.unspecified_parameters &&
4976 !is_sym_main(symbol)) {
4977 warningf(pos, "no previous prototype for '%#T'",
4980 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4981 new_storage_class = STORAGE_CLASS_EXTERN;
4990 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4991 new_storage_class == STORAGE_CLASS_EXTERN) {
4992 warn_redundant_declaration:
4993 if (!is_definition &&
4994 warning.redundant_decls &&
4995 is_type_valid(prev_type) &&
4996 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4998 "redundant declaration for '%Y' (declared %P)",
4999 symbol, &previous_entity->base.source_position);
5001 } else if (current_function == NULL) {
5002 if (old_storage_class != STORAGE_CLASS_STATIC &&
5003 new_storage_class == STORAGE_CLASS_STATIC) {
5005 "static declaration of '%Y' follows non-static declaration (declared %P)",
5006 symbol, &previous_entity->base.source_position);
5007 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5008 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5009 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5011 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5013 goto error_redeclaration;
5014 goto warn_redundant_declaration;
5016 } else if (is_type_valid(prev_type)) {
5017 if (old_storage_class == new_storage_class) {
5018 error_redeclaration:
5019 errorf(pos, "redeclaration of '%Y' (declared %P)",
5020 symbol, &previous_entity->base.source_position);
5023 "redeclaration of '%Y' with different linkage (declared %P)",
5024 symbol, &previous_entity->base.source_position);
5029 previous_declaration->modifiers |= declaration->modifiers;
5030 if (entity->kind == ENTITY_FUNCTION) {
5031 previous_entity->function.is_inline |= entity->function.is_inline;
5033 return previous_entity;
5036 if (entity->kind == ENTITY_FUNCTION) {
5037 if (is_definition &&
5038 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5039 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5040 warningf(pos, "no previous prototype for '%#T'",
5041 entity->declaration.type, symbol);
5042 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5043 warningf(pos, "no previous declaration for '%#T'",
5044 entity->declaration.type, symbol);
5047 } else if (warning.missing_declarations
5048 && entity->kind == ENTITY_VARIABLE
5049 && current_scope == file_scope) {
5050 declaration_t *declaration = &entity->declaration;
5051 if (declaration->storage_class == STORAGE_CLASS_NONE ||
5052 declaration->storage_class == STORAGE_CLASS_THREAD) {
5053 warningf(pos, "no previous declaration for '%#T'",
5054 declaration->type, symbol);
5059 assert(entity->base.parent_scope == NULL);
5060 assert(current_scope != NULL);
5062 entity->base.parent_scope = current_scope;
5063 entity->base.namespc = NAMESPACE_NORMAL;
5064 environment_push(entity);
5065 append_entity(current_scope, entity);
5070 static void parser_error_multiple_definition(entity_t *entity,
5071 const source_position_t *source_position)
5073 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5074 entity->base.symbol, &entity->base.source_position);
5077 static bool is_declaration_specifier(const token_t *token,
5078 bool only_specifiers_qualifiers)
5080 switch (token->type) {
5085 return is_typedef_symbol(token->v.symbol);
5087 case T___extension__:
5089 return !only_specifiers_qualifiers;
5096 static void parse_init_declarator_rest(entity_t *entity)
5098 assert(is_declaration(entity));
5099 declaration_t *const declaration = &entity->declaration;
5103 type_t *orig_type = declaration->type;
5104 type_t *type = skip_typeref(orig_type);
5106 if (entity->kind == ENTITY_VARIABLE
5107 && entity->variable.initializer != NULL) {
5108 parser_error_multiple_definition(entity, HERE);
5111 bool must_be_constant = false;
5112 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5113 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5114 entity->base.parent_scope == file_scope) {
5115 must_be_constant = true;
5118 if (is_type_function(type)) {
5119 errorf(&entity->base.source_position,
5120 "function '%#T' is initialized like a variable",
5121 orig_type, entity->base.symbol);
5122 orig_type = type_error_type;
5125 parse_initializer_env_t env;
5126 env.type = orig_type;
5127 env.must_be_constant = must_be_constant;
5128 env.entity = entity;
5129 current_init_decl = entity;
5131 initializer_t *initializer = parse_initializer(&env);
5132 current_init_decl = NULL;
5134 if (entity->kind == ENTITY_VARIABLE) {
5135 /* § 6.7.5 (22) array initializers for arrays with unknown size
5136 * determine the array type size */
5137 declaration->type = env.type;
5138 entity->variable.initializer = initializer;
5142 /* parse rest of a declaration without any declarator */
5143 static void parse_anonymous_declaration_rest(
5144 const declaration_specifiers_t *specifiers)
5147 anonymous_entity = NULL;
5149 if (warning.other) {
5150 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5151 warningf(&specifiers->source_position,
5152 "useless storage class in empty declaration");
5155 type_t *type = specifiers->type;
5156 switch (type->kind) {
5157 case TYPE_COMPOUND_STRUCT:
5158 case TYPE_COMPOUND_UNION: {
5159 if (type->compound.compound->base.symbol == NULL) {
5160 warningf(&specifiers->source_position,
5161 "unnamed struct/union that defines no instances");
5170 warningf(&specifiers->source_position, "empty declaration");
5176 static void check_variable_type_complete(entity_t *ent)
5178 if (ent->kind != ENTITY_VARIABLE)
5181 declaration_t *decl = &ent->declaration;
5182 if (decl->storage_class == STORAGE_CLASS_EXTERN)
5185 type_t *type = decl->type;
5186 if (!is_type_incomplete(skip_typeref(type)))
5189 errorf(&ent->base.source_position,
5190 "variable '%#T' is of incomplete type", type, ent->base.symbol);
5194 static void parse_declaration_rest(entity_t *ndeclaration,
5195 const declaration_specifiers_t *specifiers,
5196 parsed_declaration_func finished_declaration)
5198 add_anchor_token(';');
5199 add_anchor_token(',');
5201 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5203 if (token.type == '=') {
5204 parse_init_declarator_rest(entity);
5207 check_variable_type_complete(entity);
5209 if (token.type != ',')
5213 add_anchor_token('=');
5214 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5215 rem_anchor_token('=');
5220 anonymous_entity = NULL;
5221 rem_anchor_token(';');
5222 rem_anchor_token(',');
5225 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5227 symbol_t *symbol = entity->base.symbol;
5228 if (symbol == NULL) {
5229 errorf(HERE, "anonymous declaration not valid as function parameter");
5233 assert(entity->base.namespc == NAMESPACE_NORMAL);
5234 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5235 if (previous_entity == NULL
5236 || previous_entity->base.parent_scope != current_scope) {
5237 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5242 if (is_definition) {
5243 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5246 return record_entity(entity, false);
5249 static void parse_declaration(parsed_declaration_func finished_declaration)
5251 declaration_specifiers_t specifiers;
5252 memset(&specifiers, 0, sizeof(specifiers));
5254 add_anchor_token(';');
5255 parse_declaration_specifiers(&specifiers);
5256 rem_anchor_token(';');
5258 if (token.type == ';') {
5259 parse_anonymous_declaration_rest(&specifiers);
5261 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5262 parse_declaration_rest(entity, &specifiers, finished_declaration);
5266 static type_t *get_default_promoted_type(type_t *orig_type)
5268 type_t *result = orig_type;
5270 type_t *type = skip_typeref(orig_type);
5271 if (is_type_integer(type)) {
5272 result = promote_integer(type);
5273 } else if (type == type_float) {
5274 result = type_double;
5280 static void parse_kr_declaration_list(entity_t *entity)
5282 if (entity->kind != ENTITY_FUNCTION)
5285 type_t *type = skip_typeref(entity->declaration.type);
5286 assert(is_type_function(type));
5287 if (!type->function.kr_style_parameters)
5291 add_anchor_token('{');
5293 /* push function parameters */
5294 size_t const top = environment_top();
5295 scope_push(&entity->function.parameters);
5297 entity_t *parameter = entity->function.parameters.entities;
5298 for ( ; parameter != NULL; parameter = parameter->base.next) {
5299 assert(parameter->base.parent_scope == NULL);
5300 parameter->base.parent_scope = current_scope;
5301 environment_push(parameter);
5304 /* parse declaration list */
5305 while (is_declaration_specifier(&token, false)) {
5306 parse_declaration(finished_kr_declaration);
5309 /* pop function parameters */
5310 assert(current_scope == &entity->function.parameters);
5312 environment_pop_to(top);
5314 /* update function type */
5315 type_t *new_type = duplicate_type(type);
5317 function_parameter_t *parameters = NULL;
5318 function_parameter_t *last_parameter = NULL;
5320 entity_t *parameter_declaration = entity->function.parameters.entities;
5321 for (; parameter_declaration != NULL;
5322 parameter_declaration = parameter_declaration->base.next) {
5323 type_t *parameter_type = parameter_declaration->declaration.type;
5324 if (parameter_type == NULL) {
5326 errorf(HERE, "no type specified for function parameter '%Y'",
5327 parameter_declaration->base.symbol);
5329 if (warning.implicit_int) {
5330 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5331 parameter_declaration->base.symbol);
5333 parameter_type = type_int;
5334 parameter_declaration->declaration.type = parameter_type;
5338 semantic_parameter(¶meter_declaration->declaration);
5339 parameter_type = parameter_declaration->declaration.type;
5342 * we need the default promoted types for the function type
5344 parameter_type = get_default_promoted_type(parameter_type);
5346 function_parameter_t *function_parameter
5347 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5348 memset(function_parameter, 0, sizeof(function_parameter[0]));
5350 function_parameter->type = parameter_type;
5351 if (last_parameter != NULL) {
5352 last_parameter->next = function_parameter;
5354 parameters = function_parameter;
5356 last_parameter = function_parameter;
5359 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5361 new_type->function.parameters = parameters;
5362 new_type->function.unspecified_parameters = true;
5364 type = typehash_insert(new_type);
5365 if (type != new_type) {
5366 obstack_free(type_obst, new_type);
5369 entity->declaration.type = type;
5371 rem_anchor_token('{');
5374 static bool first_err = true;
5377 * When called with first_err set, prints the name of the current function,
5380 static void print_in_function(void)
5384 diagnosticf("%s: In function '%Y':\n",
5385 current_function->base.base.source_position.input_name,
5386 current_function->base.base.symbol);
5391 * Check if all labels are defined in the current function.
5392 * Check if all labels are used in the current function.
5394 static void check_labels(void)
5396 for (const goto_statement_t *goto_statement = goto_first;
5397 goto_statement != NULL;
5398 goto_statement = goto_statement->next) {
5399 /* skip computed gotos */
5400 if (goto_statement->expression != NULL)
5403 label_t *label = goto_statement->label;
5406 if (label->base.source_position.input_name == NULL) {
5407 print_in_function();
5408 errorf(&goto_statement->base.source_position,
5409 "label '%Y' used but not defined", label->base.symbol);
5413 if (warning.unused_label) {
5414 for (const label_statement_t *label_statement = label_first;
5415 label_statement != NULL;
5416 label_statement = label_statement->next) {
5417 label_t *label = label_statement->label;
5419 if (! label->used) {
5420 print_in_function();
5421 warningf(&label_statement->base.source_position,
5422 "label '%Y' defined but not used", label->base.symbol);
5428 static void warn_unused_decl(entity_t *entity, entity_t *end,
5429 char const *const what)
5431 for (; entity != NULL; entity = entity->base.next) {
5432 if (!is_declaration(entity))
5435 declaration_t *declaration = &entity->declaration;
5436 if (declaration->implicit)
5439 if (!declaration->used) {
5440 print_in_function();
5441 warningf(&entity->base.source_position, "%s '%Y' is unused",
5442 what, entity->base.symbol);
5443 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5444 print_in_function();
5445 warningf(&entity->base.source_position, "%s '%Y' is never read",
5446 what, entity->base.symbol);
5454 static void check_unused_variables(statement_t *const stmt, void *const env)
5458 switch (stmt->kind) {
5459 case STATEMENT_DECLARATION: {
5460 declaration_statement_t const *const decls = &stmt->declaration;
5461 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5467 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5476 * Check declarations of current_function for unused entities.
5478 static void check_declarations(void)
5480 if (warning.unused_parameter) {
5481 const scope_t *scope = ¤t_function->parameters;
5483 /* do not issue unused warnings for main */
5484 if (!is_sym_main(current_function->base.base.symbol)) {
5485 warn_unused_decl(scope->entities, NULL, "parameter");
5488 if (warning.unused_variable) {
5489 walk_statements(current_function->statement, check_unused_variables,
5494 static int determine_truth(expression_t const* const cond)
5497 !is_constant_expression(cond) ? 0 :
5498 fold_constant(cond) != 0 ? 1 :
5502 static bool expression_returns(expression_t const *const expr)
5504 switch (expr->kind) {
5506 expression_t const *const func = expr->call.function;
5507 if (func->kind == EXPR_REFERENCE) {
5508 entity_t *entity = func->reference.entity;
5509 if (entity->kind == ENTITY_FUNCTION
5510 && entity->declaration.modifiers & DM_NORETURN)
5514 if (!expression_returns(func))
5517 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5518 if (!expression_returns(arg->expression))
5525 case EXPR_REFERENCE:
5526 case EXPR_REFERENCE_ENUM_VALUE:
5528 case EXPR_CHARACTER_CONSTANT:
5529 case EXPR_WIDE_CHARACTER_CONSTANT:
5530 case EXPR_STRING_LITERAL:
5531 case EXPR_WIDE_STRING_LITERAL:
5532 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5533 case EXPR_LABEL_ADDRESS:
5534 case EXPR_CLASSIFY_TYPE:
5535 case EXPR_SIZEOF: // TODO handle obscure VLA case
5538 case EXPR_BUILTIN_SYMBOL:
5539 case EXPR_BUILTIN_CONSTANT_P:
5540 case EXPR_BUILTIN_PREFETCH:
5543 case EXPR_STATEMENT: // TODO implement
5546 case EXPR_CONDITIONAL:
5547 // TODO handle constant expression
5549 expression_returns(expr->conditional.condition) && (
5550 expression_returns(expr->conditional.true_expression) ||
5551 expression_returns(expr->conditional.false_expression)
5555 return expression_returns(expr->select.compound);
5557 case EXPR_ARRAY_ACCESS:
5559 expression_returns(expr->array_access.array_ref) &&
5560 expression_returns(expr->array_access.index);
5563 return expression_returns(expr->va_starte.ap);
5566 return expression_returns(expr->va_arge.ap);
5568 EXPR_UNARY_CASES_MANDATORY
5569 return expression_returns(expr->unary.value);
5571 case EXPR_UNARY_THROW:
5575 // TODO handle constant lhs of && and ||
5577 expression_returns(expr->binary.left) &&
5578 expression_returns(expr->binary.right);
5584 panic("unhandled expression");
5587 static bool noreturn_candidate;
5589 static void check_reachable(statement_t *const stmt)
5591 if (stmt->base.reachable)
5593 if (stmt->kind != STATEMENT_DO_WHILE)
5594 stmt->base.reachable = true;
5596 statement_t *last = stmt;
5598 switch (stmt->kind) {
5599 case STATEMENT_INVALID:
5600 case STATEMENT_EMPTY:
5601 case STATEMENT_DECLARATION:
5602 case STATEMENT_LOCAL_LABEL:
5604 next = stmt->base.next;
5607 case STATEMENT_COMPOUND:
5608 next = stmt->compound.statements;
5611 case STATEMENT_RETURN:
5612 noreturn_candidate = false;
5615 case STATEMENT_IF: {
5616 if_statement_t const* const ifs = &stmt->ifs;
5617 int const val = determine_truth(ifs->condition);
5620 check_reachable(ifs->true_statement);
5625 if (ifs->false_statement != NULL) {
5626 check_reachable(ifs->false_statement);
5630 next = stmt->base.next;
5634 case STATEMENT_SWITCH: {
5635 switch_statement_t const *const switchs = &stmt->switchs;
5636 expression_t const *const expr = switchs->expression;
5638 if (is_constant_expression(expr)) {
5639 long const val = fold_constant(expr);
5640 case_label_statement_t * defaults = NULL;
5641 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5642 if (i->expression == NULL) {
5647 if (i->first_case <= val && val <= i->last_case) {
5648 check_reachable((statement_t*)i);
5653 if (defaults != NULL) {
5654 check_reachable((statement_t*)defaults);
5658 bool has_default = false;
5659 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5660 if (i->expression == NULL)
5663 check_reachable((statement_t*)i);
5670 next = stmt->base.next;
5674 case STATEMENT_EXPRESSION: {
5675 /* Check for noreturn function call */
5676 expression_t const *const expr = stmt->expression.expression;
5677 if (!expression_returns(expr))
5680 next = stmt->base.next;
5684 case STATEMENT_CONTINUE: {
5685 statement_t *parent = stmt;
5687 parent = parent->base.parent;
5688 if (parent == NULL) /* continue not within loop */
5692 switch (parent->kind) {
5693 case STATEMENT_WHILE: goto continue_while;
5694 case STATEMENT_DO_WHILE: goto continue_do_while;
5695 case STATEMENT_FOR: goto continue_for;
5702 case STATEMENT_BREAK: {
5703 statement_t *parent = stmt;
5705 parent = parent->base.parent;
5706 if (parent == NULL) /* break not within loop/switch */
5709 switch (parent->kind) {
5710 case STATEMENT_SWITCH:
5711 case STATEMENT_WHILE:
5712 case STATEMENT_DO_WHILE:
5715 next = parent->base.next;
5716 goto found_break_parent;
5725 case STATEMENT_GOTO:
5726 if (stmt->gotos.expression) {
5727 statement_t *parent = stmt->base.parent;
5728 if (parent == NULL) /* top level goto */
5732 next = stmt->gotos.label->statement;
5733 if (next == NULL) /* missing label */
5738 case STATEMENT_LABEL:
5739 next = stmt->label.statement;
5742 case STATEMENT_CASE_LABEL:
5743 next = stmt->case_label.statement;
5746 case STATEMENT_WHILE: {
5747 while_statement_t const *const whiles = &stmt->whiles;
5748 int const val = determine_truth(whiles->condition);
5751 check_reachable(whiles->body);
5756 next = stmt->base.next;
5760 case STATEMENT_DO_WHILE:
5761 next = stmt->do_while.body;
5764 case STATEMENT_FOR: {
5765 for_statement_t *const fors = &stmt->fors;
5767 if (fors->condition_reachable)
5769 fors->condition_reachable = true;
5771 expression_t const *const cond = fors->condition;
5773 cond == NULL ? 1 : determine_truth(cond);
5776 check_reachable(fors->body);
5781 next = stmt->base.next;
5785 case STATEMENT_MS_TRY: {
5786 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5787 check_reachable(ms_try->try_statement);
5788 next = ms_try->final_statement;
5792 case STATEMENT_LEAVE: {
5793 statement_t *parent = stmt;
5795 parent = parent->base.parent;
5796 if (parent == NULL) /* __leave not within __try */
5799 if (parent->kind == STATEMENT_MS_TRY) {
5801 next = parent->ms_try.final_statement;
5809 while (next == NULL) {
5810 next = last->base.parent;
5812 noreturn_candidate = false;
5814 type_t *const type = current_function->base.type;
5815 assert(is_type_function(type));
5816 type_t *const ret = skip_typeref(type->function.return_type);
5817 if (warning.return_type &&
5818 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5819 is_type_valid(ret) &&
5820 !is_sym_main(current_function->base.base.symbol)) {
5821 warningf(&stmt->base.source_position,
5822 "control reaches end of non-void function");
5827 switch (next->kind) {
5828 case STATEMENT_INVALID:
5829 case STATEMENT_EMPTY:
5830 case STATEMENT_DECLARATION:
5831 case STATEMENT_LOCAL_LABEL:
5832 case STATEMENT_EXPRESSION:
5834 case STATEMENT_RETURN:
5835 case STATEMENT_CONTINUE:
5836 case STATEMENT_BREAK:
5837 case STATEMENT_GOTO:
5838 case STATEMENT_LEAVE:
5839 panic("invalid control flow in function");
5841 case STATEMENT_COMPOUND:
5843 case STATEMENT_SWITCH:
5844 case STATEMENT_LABEL:
5845 case STATEMENT_CASE_LABEL:
5847 next = next->base.next;
5850 case STATEMENT_WHILE: {
5852 if (next->base.reachable)
5854 next->base.reachable = true;
5856 while_statement_t const *const whiles = &next->whiles;
5857 int const val = determine_truth(whiles->condition);
5860 check_reachable(whiles->body);
5866 next = next->base.next;
5870 case STATEMENT_DO_WHILE: {
5872 if (next->base.reachable)
5874 next->base.reachable = true;
5876 do_while_statement_t const *const dw = &next->do_while;
5877 int const val = determine_truth(dw->condition);
5880 check_reachable(dw->body);
5886 next = next->base.next;
5890 case STATEMENT_FOR: {
5892 for_statement_t *const fors = &next->fors;
5894 fors->step_reachable = true;
5896 if (fors->condition_reachable)
5898 fors->condition_reachable = true;
5900 expression_t const *const cond = fors->condition;
5902 cond == NULL ? 1 : determine_truth(cond);
5905 check_reachable(fors->body);
5911 next = next->base.next;
5915 case STATEMENT_MS_TRY:
5917 next = next->ms_try.final_statement;
5922 check_reachable(next);
5925 static void check_unreachable(statement_t* const stmt, void *const env)
5929 switch (stmt->kind) {
5930 case STATEMENT_DO_WHILE:
5931 if (!stmt->base.reachable) {
5932 expression_t const *const cond = stmt->do_while.condition;
5933 if (determine_truth(cond) >= 0) {
5934 warningf(&cond->base.source_position,
5935 "condition of do-while-loop is unreachable");
5940 case STATEMENT_FOR: {
5941 for_statement_t const* const fors = &stmt->fors;
5943 // if init and step are unreachable, cond is unreachable, too
5944 if (!stmt->base.reachable && !fors->step_reachable) {
5945 warningf(&stmt->base.source_position, "statement is unreachable");
5947 if (!stmt->base.reachable && fors->initialisation != NULL) {
5948 warningf(&fors->initialisation->base.source_position,
5949 "initialisation of for-statement is unreachable");
5952 if (!fors->condition_reachable && fors->condition != NULL) {
5953 warningf(&fors->condition->base.source_position,
5954 "condition of for-statement is unreachable");
5957 if (!fors->step_reachable && fors->step != NULL) {
5958 warningf(&fors->step->base.source_position,
5959 "step of for-statement is unreachable");
5965 case STATEMENT_COMPOUND:
5966 if (stmt->compound.statements != NULL)
5971 if (!stmt->base.reachable)
5972 warningf(&stmt->base.source_position, "statement is unreachable");
5977 static void parse_external_declaration(void)
5979 /* function-definitions and declarations both start with declaration
5981 declaration_specifiers_t specifiers;
5982 memset(&specifiers, 0, sizeof(specifiers));
5984 add_anchor_token(';');
5985 parse_declaration_specifiers(&specifiers);
5986 rem_anchor_token(';');
5988 /* must be a declaration */
5989 if (token.type == ';') {
5990 parse_anonymous_declaration_rest(&specifiers);
5994 add_anchor_token(',');
5995 add_anchor_token('=');
5996 add_anchor_token(';');
5997 add_anchor_token('{');
5999 /* declarator is common to both function-definitions and declarations */
6000 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
6002 rem_anchor_token('{');
6003 rem_anchor_token(';');
6004 rem_anchor_token('=');
6005 rem_anchor_token(',');
6007 /* must be a declaration */
6008 switch (token.type) {
6012 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6016 /* must be a function definition */
6017 parse_kr_declaration_list(ndeclaration);
6019 if (token.type != '{') {
6020 parse_error_expected("while parsing function definition", '{', NULL);
6021 eat_until_matching_token(';');
6025 assert(is_declaration(ndeclaration));
6026 type_t *type = skip_typeref(ndeclaration->declaration.type);
6028 if (!is_type_function(type)) {
6029 if (is_type_valid(type)) {
6030 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6031 type, ndeclaration->base.symbol);
6037 if (warning.aggregate_return &&
6038 is_type_compound(skip_typeref(type->function.return_type))) {
6039 warningf(HERE, "function '%Y' returns an aggregate",
6040 ndeclaration->base.symbol);
6042 if (warning.traditional && !type->function.unspecified_parameters) {
6043 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6044 ndeclaration->base.symbol);
6046 if (warning.old_style_definition && type->function.unspecified_parameters) {
6047 warningf(HERE, "old-style function definition '%Y'",
6048 ndeclaration->base.symbol);
6051 /* § 6.7.5.3 (14) a function definition with () means no
6052 * parameters (and not unspecified parameters) */
6053 if (type->function.unspecified_parameters
6054 && type->function.parameters == NULL
6055 && !type->function.kr_style_parameters) {
6056 type_t *duplicate = duplicate_type(type);
6057 duplicate->function.unspecified_parameters = false;
6059 type = typehash_insert(duplicate);
6060 if (type != duplicate) {
6061 obstack_free(type_obst, duplicate);
6063 ndeclaration->declaration.type = type;
6066 entity_t *const entity = record_entity(ndeclaration, true);
6067 assert(entity->kind == ENTITY_FUNCTION);
6068 assert(ndeclaration->kind == ENTITY_FUNCTION);
6070 function_t *function = &entity->function;
6071 if (ndeclaration != entity) {
6072 function->parameters = ndeclaration->function.parameters;
6074 assert(is_declaration(entity));
6075 type = skip_typeref(entity->declaration.type);
6077 /* push function parameters and switch scope */
6078 size_t const top = environment_top();
6079 scope_push(&function->parameters);
6081 entity_t *parameter = function->parameters.entities;
6082 for (; parameter != NULL; parameter = parameter->base.next) {
6083 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6084 parameter->base.parent_scope = current_scope;
6086 assert(parameter->base.parent_scope == NULL
6087 || parameter->base.parent_scope == current_scope);
6088 parameter->base.parent_scope = current_scope;
6089 if (parameter->base.symbol == NULL) {
6090 errorf(¶meter->base.source_position, "parameter name omitted");
6093 environment_push(parameter);
6096 if (function->statement != NULL) {
6097 parser_error_multiple_definition(entity, HERE);
6100 /* parse function body */
6101 int label_stack_top = label_top();
6102 function_t *old_current_function = current_function;
6103 current_function = function;
6104 current_parent = NULL;
6107 goto_anchor = &goto_first;
6109 label_anchor = &label_first;
6111 statement_t *const body = parse_compound_statement(false);
6112 function->statement = body;
6115 check_declarations();
6116 if (warning.return_type ||
6117 warning.unreachable_code ||
6118 (warning.missing_noreturn
6119 && !(function->base.modifiers & DM_NORETURN))) {
6120 noreturn_candidate = true;
6121 check_reachable(body);
6122 if (warning.unreachable_code)
6123 walk_statements(body, check_unreachable, NULL);
6124 if (warning.missing_noreturn &&
6125 noreturn_candidate &&
6126 !(function->base.modifiers & DM_NORETURN)) {
6127 warningf(&body->base.source_position,
6128 "function '%#T' is candidate for attribute 'noreturn'",
6129 type, entity->base.symbol);
6133 assert(current_parent == NULL);
6134 assert(current_function == function);
6135 current_function = old_current_function;
6136 label_pop_to(label_stack_top);
6139 assert(current_scope == &function->parameters);
6141 environment_pop_to(top);
6144 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6145 source_position_t *source_position,
6146 const symbol_t *symbol)
6148 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6150 type->bitfield.base_type = base_type;
6151 type->bitfield.size_expression = size;
6154 type_t *skipped_type = skip_typeref(base_type);
6155 if (!is_type_integer(skipped_type)) {
6156 errorf(HERE, "bitfield base type '%T' is not an integer type",
6160 bit_size = skipped_type->base.size * 8;
6163 if (is_constant_expression(size)) {
6164 long v = fold_constant(size);
6167 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6168 } else if (v == 0) {
6169 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6170 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6171 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6173 type->bitfield.bit_size = v;
6180 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6182 entity_t *iter = compound->members.entities;
6183 for (; iter != NULL; iter = iter->base.next) {
6184 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6187 if (iter->base.symbol == symbol) {
6189 } else if (iter->base.symbol == NULL) {
6190 type_t *type = skip_typeref(iter->declaration.type);
6191 if (is_type_compound(type)) {
6193 = find_compound_entry(type->compound.compound, symbol);
6204 static void parse_compound_declarators(compound_t *compound,
6205 const declaration_specifiers_t *specifiers)
6210 if (token.type == ':') {
6211 source_position_t source_position = *HERE;
6214 type_t *base_type = specifiers->type;
6215 expression_t *size = parse_constant_expression();
6217 type_t *type = make_bitfield_type(base_type, size,
6218 &source_position, sym_anonymous);
6220 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6221 entity->base.namespc = NAMESPACE_NORMAL;
6222 entity->base.source_position = source_position;
6223 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6224 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6225 entity->declaration.modifiers = specifiers->modifiers;
6226 entity->declaration.type = type;
6228 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6229 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6231 if (token.type == ':') {
6232 source_position_t source_position = *HERE;
6234 expression_t *size = parse_constant_expression();
6236 type_t *type = entity->declaration.type;
6237 type_t *bitfield_type = make_bitfield_type(type, size,
6238 &source_position, entity->base.symbol);
6239 entity->declaration.type = bitfield_type;
6243 /* make sure we don't define a symbol multiple times */
6244 symbol_t *symbol = entity->base.symbol;
6245 if (symbol != NULL) {
6246 entity_t *prev = find_compound_entry(compound, symbol);
6249 errorf(&entity->base.source_position,
6250 "multiple declarations of symbol '%Y' (declared %P)",
6251 symbol, &prev->base.source_position);
6255 append_entity(&compound->members, entity);
6257 type_t *orig_type = entity->declaration.type;
6258 type_t *type = skip_typeref(orig_type);
6259 if (is_type_function(type)) {
6260 errorf(&entity->base.source_position,
6261 "compound member '%Y' must not have function type '%T'",
6262 entity->base.symbol, orig_type);
6263 } else if (is_type_incomplete(type)) {
6264 /* §6.7.2.1:16 flexible array member */
6265 if (is_type_array(type) &&
6266 token.type == ';' &&
6267 look_ahead(1)->type == '}') {
6268 compound->has_flexible_member = true;
6270 errorf(&entity->base.source_position,
6271 "compound member '%Y' has incomplete type '%T'",
6272 entity->base.symbol, orig_type);
6276 if (token.type != ',')
6283 anonymous_entity = NULL;
6286 static void parse_compound_type_entries(compound_t *compound)
6289 add_anchor_token('}');
6291 while (token.type != '}') {
6292 if (token.type == T_EOF) {
6293 errorf(HERE, "EOF while parsing struct");
6296 declaration_specifiers_t specifiers;
6297 memset(&specifiers, 0, sizeof(specifiers));
6298 parse_declaration_specifiers(&specifiers);
6300 parse_compound_declarators(compound, &specifiers);
6302 rem_anchor_token('}');
6306 compound->complete = true;
6309 static type_t *parse_typename(void)
6311 declaration_specifiers_t specifiers;
6312 memset(&specifiers, 0, sizeof(specifiers));
6313 parse_declaration_specifiers(&specifiers);
6314 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6315 /* TODO: improve error message, user does probably not know what a
6316 * storage class is...
6318 errorf(HERE, "typename may not have a storage class");
6321 type_t *result = parse_abstract_declarator(specifiers.type);
6329 typedef expression_t* (*parse_expression_function)(void);
6330 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6332 typedef struct expression_parser_function_t expression_parser_function_t;
6333 struct expression_parser_function_t {
6334 parse_expression_function parser;
6335 unsigned infix_precedence;
6336 parse_expression_infix_function infix_parser;
6339 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6342 * Prints an error message if an expression was expected but not read
6344 static expression_t *expected_expression_error(void)
6346 /* skip the error message if the error token was read */
6347 if (token.type != T_ERROR) {
6348 errorf(HERE, "expected expression, got token '%K'", &token);
6352 return create_invalid_expression();
6356 * Parse a string constant.
6358 static expression_t *parse_string_const(void)
6361 if (token.type == T_STRING_LITERAL) {
6362 string_t res = token.v.string;
6364 while (token.type == T_STRING_LITERAL) {
6365 res = concat_strings(&res, &token.v.string);
6368 if (token.type != T_WIDE_STRING_LITERAL) {
6369 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6370 /* note: that we use type_char_ptr here, which is already the
6371 * automatic converted type. revert_automatic_type_conversion
6372 * will construct the array type */
6373 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6374 cnst->string.value = res;
6378 wres = concat_string_wide_string(&res, &token.v.wide_string);
6380 wres = token.v.wide_string;
6385 switch (token.type) {
6386 case T_WIDE_STRING_LITERAL:
6387 wres = concat_wide_strings(&wres, &token.v.wide_string);
6390 case T_STRING_LITERAL:
6391 wres = concat_wide_string_string(&wres, &token.v.string);
6395 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6396 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6397 cnst->wide_string.value = wres;
6406 * Parse a boolean constant.
6408 static expression_t *parse_bool_const(bool value)
6410 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6411 cnst->base.type = type_bool;
6412 cnst->conste.v.int_value = value;
6420 * Parse an integer constant.
6422 static expression_t *parse_int_const(void)
6424 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6425 cnst->base.type = token.datatype;
6426 cnst->conste.v.int_value = token.v.intvalue;
6434 * Parse a character constant.
6436 static expression_t *parse_character_constant(void)
6438 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6439 cnst->base.type = token.datatype;
6440 cnst->conste.v.character = token.v.string;
6442 if (cnst->conste.v.character.size != 1) {
6444 errorf(HERE, "more than 1 character in character constant");
6445 } else if (warning.multichar) {
6446 warningf(HERE, "multi-character character constant");
6455 * Parse a wide character constant.
6457 static expression_t *parse_wide_character_constant(void)
6459 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6460 cnst->base.type = token.datatype;
6461 cnst->conste.v.wide_character = token.v.wide_string;
6463 if (cnst->conste.v.wide_character.size != 1) {
6465 errorf(HERE, "more than 1 character in character constant");
6466 } else if (warning.multichar) {
6467 warningf(HERE, "multi-character character constant");
6476 * Parse a float constant.
6478 static expression_t *parse_float_const(void)
6480 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6481 cnst->base.type = token.datatype;
6482 cnst->conste.v.float_value = token.v.floatvalue;
6489 static entity_t *create_implicit_function(symbol_t *symbol,
6490 const source_position_t *source_position)
6492 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6493 ntype->function.return_type = type_int;
6494 ntype->function.unspecified_parameters = true;
6496 type_t *type = typehash_insert(ntype);
6497 if (type != ntype) {
6501 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6502 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6503 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6504 entity->declaration.type = type;
6505 entity->declaration.implicit = true;
6506 entity->base.symbol = symbol;
6507 entity->base.source_position = *source_position;
6509 bool strict_prototypes_old = warning.strict_prototypes;
6510 warning.strict_prototypes = false;
6511 record_entity(entity, false);
6512 warning.strict_prototypes = strict_prototypes_old;
6518 * Creates a return_type (func)(argument_type) function type if not
6521 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6522 type_t *argument_type2)
6524 function_parameter_t *parameter2
6525 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6526 memset(parameter2, 0, sizeof(parameter2[0]));
6527 parameter2->type = argument_type2;
6529 function_parameter_t *parameter1
6530 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6531 memset(parameter1, 0, sizeof(parameter1[0]));
6532 parameter1->type = argument_type1;
6533 parameter1->next = parameter2;
6535 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6536 type->function.return_type = return_type;
6537 type->function.parameters = parameter1;
6539 type_t *result = typehash_insert(type);
6540 if (result != type) {
6548 * Creates a return_type (func)(argument_type) function type if not
6551 * @param return_type the return type
6552 * @param argument_type the argument type
6554 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6556 function_parameter_t *parameter
6557 = obstack_alloc(type_obst, sizeof(parameter[0]));
6558 memset(parameter, 0, sizeof(parameter[0]));
6559 parameter->type = argument_type;
6561 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6562 type->function.return_type = return_type;
6563 type->function.parameters = parameter;
6565 type_t *result = typehash_insert(type);
6566 if (result != type) {
6573 static type_t *make_function_0_type(type_t *return_type)
6575 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6576 type->function.return_type = return_type;
6577 type->function.parameters = NULL;
6579 type_t *result = typehash_insert(type);
6580 if (result != type) {
6588 * Creates a function type for some function like builtins.
6590 * @param symbol the symbol describing the builtin
6592 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6594 switch (symbol->ID) {
6595 case T___builtin_alloca:
6596 return make_function_1_type(type_void_ptr, type_size_t);
6597 case T___builtin_huge_val:
6598 return make_function_0_type(type_double);
6599 case T___builtin_inf:
6600 return make_function_0_type(type_double);
6601 case T___builtin_inff:
6602 return make_function_0_type(type_float);
6603 case T___builtin_infl:
6604 return make_function_0_type(type_long_double);
6605 case T___builtin_nan:
6606 return make_function_1_type(type_double, type_char_ptr);
6607 case T___builtin_nanf:
6608 return make_function_1_type(type_float, type_char_ptr);
6609 case T___builtin_nanl:
6610 return make_function_1_type(type_long_double, type_char_ptr);
6611 case T___builtin_va_end:
6612 return make_function_1_type(type_void, type_valist);
6613 case T___builtin_expect:
6614 return make_function_2_type(type_long, type_long, type_long);
6616 internal_errorf(HERE, "not implemented builtin symbol found");
6621 * Performs automatic type cast as described in § 6.3.2.1.
6623 * @param orig_type the original type
6625 static type_t *automatic_type_conversion(type_t *orig_type)
6627 type_t *type = skip_typeref(orig_type);
6628 if (is_type_array(type)) {
6629 array_type_t *array_type = &type->array;
6630 type_t *element_type = array_type->element_type;
6631 unsigned qualifiers = array_type->base.qualifiers;
6633 return make_pointer_type(element_type, qualifiers);
6636 if (is_type_function(type)) {
6637 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6644 * reverts the automatic casts of array to pointer types and function
6645 * to function-pointer types as defined § 6.3.2.1
6647 type_t *revert_automatic_type_conversion(const expression_t *expression)
6649 switch (expression->kind) {
6650 case EXPR_REFERENCE: {
6651 entity_t *entity = expression->reference.entity;
6652 if (is_declaration(entity)) {
6653 return entity->declaration.type;
6654 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6655 return entity->enum_value.enum_type;
6657 panic("no declaration or enum in reference");
6662 entity_t *entity = expression->select.compound_entry;
6663 assert(is_declaration(entity));
6664 type_t *type = entity->declaration.type;
6665 return get_qualified_type(type,
6666 expression->base.type->base.qualifiers);
6669 case EXPR_UNARY_DEREFERENCE: {
6670 const expression_t *const value = expression->unary.value;
6671 type_t *const type = skip_typeref(value->base.type);
6672 assert(is_type_pointer(type));
6673 return type->pointer.points_to;
6676 case EXPR_BUILTIN_SYMBOL:
6677 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6679 case EXPR_ARRAY_ACCESS: {
6680 const expression_t *array_ref = expression->array_access.array_ref;
6681 type_t *type_left = skip_typeref(array_ref->base.type);
6682 if (!is_type_valid(type_left))
6684 assert(is_type_pointer(type_left));
6685 return type_left->pointer.points_to;
6688 case EXPR_STRING_LITERAL: {
6689 size_t size = expression->string.value.size;
6690 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6693 case EXPR_WIDE_STRING_LITERAL: {
6694 size_t size = expression->wide_string.value.size;
6695 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6698 case EXPR_COMPOUND_LITERAL:
6699 return expression->compound_literal.type;
6704 return expression->base.type;
6707 static expression_t *parse_reference(void)
6709 symbol_t *const symbol = token.v.symbol;
6711 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6713 if (entity == NULL) {
6714 if (!strict_mode && look_ahead(1)->type == '(') {
6715 /* an implicitly declared function */
6716 if (warning.implicit_function_declaration) {
6717 warningf(HERE, "implicit declaration of function '%Y'",
6721 entity = create_implicit_function(symbol, HERE);
6723 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6724 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6730 if (is_declaration(entity)) {
6731 orig_type = entity->declaration.type;
6732 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6733 orig_type = entity->enum_value.enum_type;
6734 } else if (entity->kind == ENTITY_TYPEDEF) {
6735 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6738 return create_invalid_expression();
6740 panic("expected declaration or enum value in reference");
6743 /* we always do the auto-type conversions; the & and sizeof parser contains
6744 * code to revert this! */
6745 type_t *type = automatic_type_conversion(orig_type);
6747 expression_kind_t kind = EXPR_REFERENCE;
6748 if (entity->kind == ENTITY_ENUM_VALUE)
6749 kind = EXPR_REFERENCE_ENUM_VALUE;
6751 expression_t *expression = allocate_expression_zero(kind);
6752 expression->reference.entity = entity;
6753 expression->base.type = type;
6755 /* this declaration is used */
6756 if (is_declaration(entity)) {
6757 entity->declaration.used = true;
6760 if (entity->base.parent_scope != file_scope
6761 && entity->base.parent_scope->depth < current_function->parameters.depth
6762 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6763 if (entity->kind == ENTITY_VARIABLE) {
6764 /* access of a variable from an outer function */
6765 entity->variable.address_taken = true;
6767 current_function->need_closure = true;
6770 /* check for deprecated functions */
6771 if (warning.deprecated_declarations
6772 && is_declaration(entity)
6773 && entity->declaration.modifiers & DM_DEPRECATED) {
6774 declaration_t *declaration = &entity->declaration;
6776 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6777 "function" : "variable";
6779 if (declaration->deprecated_string != NULL) {
6780 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6781 prefix, entity->base.symbol, &entity->base.source_position,
6782 declaration->deprecated_string);
6784 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6785 entity->base.symbol, &entity->base.source_position);
6789 if (warning.init_self && entity == current_init_decl && !in_type_prop
6790 && entity->kind == ENTITY_VARIABLE) {
6791 current_init_decl = NULL;
6792 warningf(HERE, "variable '%#T' is initialized by itself",
6793 entity->declaration.type, entity->base.symbol);
6800 static bool semantic_cast(expression_t *cast)
6802 expression_t *expression = cast->unary.value;
6803 type_t *orig_dest_type = cast->base.type;
6804 type_t *orig_type_right = expression->base.type;
6805 type_t const *dst_type = skip_typeref(orig_dest_type);
6806 type_t const *src_type = skip_typeref(orig_type_right);
6807 source_position_t const *pos = &cast->base.source_position;
6809 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6810 if (dst_type == type_void)
6813 /* only integer and pointer can be casted to pointer */
6814 if (is_type_pointer(dst_type) &&
6815 !is_type_pointer(src_type) &&
6816 !is_type_integer(src_type) &&
6817 is_type_valid(src_type)) {
6818 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6822 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6823 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6827 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6828 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6832 if (warning.cast_qual &&
6833 is_type_pointer(src_type) &&
6834 is_type_pointer(dst_type)) {
6835 type_t *src = skip_typeref(src_type->pointer.points_to);
6836 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6837 unsigned missing_qualifiers =
6838 src->base.qualifiers & ~dst->base.qualifiers;
6839 if (missing_qualifiers != 0) {
6841 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6842 missing_qualifiers, orig_type_right);
6848 static expression_t *parse_compound_literal(type_t *type)
6850 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6852 parse_initializer_env_t env;
6855 env.must_be_constant = false;
6856 initializer_t *initializer = parse_initializer(&env);
6859 expression->compound_literal.initializer = initializer;
6860 expression->compound_literal.type = type;
6861 expression->base.type = automatic_type_conversion(type);
6867 * Parse a cast expression.
6869 static expression_t *parse_cast(void)
6871 add_anchor_token(')');
6873 source_position_t source_position = token.source_position;
6875 type_t *type = parse_typename();
6877 rem_anchor_token(')');
6880 if (token.type == '{') {
6881 return parse_compound_literal(type);
6884 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6885 cast->base.source_position = source_position;
6887 expression_t *value = parse_sub_expression(PREC_CAST);
6888 cast->base.type = type;
6889 cast->unary.value = value;
6891 if (! semantic_cast(cast)) {
6892 /* TODO: record the error in the AST. else it is impossible to detect it */
6897 return create_invalid_expression();
6901 * Parse a statement expression.
6903 static expression_t *parse_statement_expression(void)
6905 add_anchor_token(')');
6907 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6909 statement_t *statement = parse_compound_statement(true);
6910 expression->statement.statement = statement;
6912 /* find last statement and use its type */
6913 type_t *type = type_void;
6914 const statement_t *stmt = statement->compound.statements;
6916 while (stmt->base.next != NULL)
6917 stmt = stmt->base.next;
6919 if (stmt->kind == STATEMENT_EXPRESSION) {
6920 type = stmt->expression.expression->base.type;
6922 } else if (warning.other) {
6923 warningf(&expression->base.source_position, "empty statement expression ({})");
6925 expression->base.type = type;
6927 rem_anchor_token(')');
6935 * Parse a parenthesized expression.
6937 static expression_t *parse_parenthesized_expression(void)
6941 switch (token.type) {
6943 /* gcc extension: a statement expression */
6944 return parse_statement_expression();
6948 return parse_cast();
6950 if (is_typedef_symbol(token.v.symbol)) {
6951 return parse_cast();
6955 add_anchor_token(')');
6956 expression_t *result = parse_expression();
6957 rem_anchor_token(')');
6964 static expression_t *parse_function_keyword(void)
6968 if (current_function == NULL) {
6969 errorf(HERE, "'__func__' used outside of a function");
6972 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6973 expression->base.type = type_char_ptr;
6974 expression->funcname.kind = FUNCNAME_FUNCTION;
6981 static expression_t *parse_pretty_function_keyword(void)
6983 if (current_function == NULL) {
6984 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6987 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6988 expression->base.type = type_char_ptr;
6989 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6991 eat(T___PRETTY_FUNCTION__);
6996 static expression_t *parse_funcsig_keyword(void)
6998 if (current_function == NULL) {
6999 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7002 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7003 expression->base.type = type_char_ptr;
7004 expression->funcname.kind = FUNCNAME_FUNCSIG;
7011 static expression_t *parse_funcdname_keyword(void)
7013 if (current_function == NULL) {
7014 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7017 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7018 expression->base.type = type_char_ptr;
7019 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7021 eat(T___FUNCDNAME__);
7026 static designator_t *parse_designator(void)
7028 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7029 result->source_position = *HERE;
7031 if (token.type != T_IDENTIFIER) {
7032 parse_error_expected("while parsing member designator",
7033 T_IDENTIFIER, NULL);
7036 result->symbol = token.v.symbol;
7039 designator_t *last_designator = result;
7041 if (token.type == '.') {
7043 if (token.type != T_IDENTIFIER) {
7044 parse_error_expected("while parsing member designator",
7045 T_IDENTIFIER, NULL);
7048 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7049 designator->source_position = *HERE;
7050 designator->symbol = token.v.symbol;
7053 last_designator->next = designator;
7054 last_designator = designator;
7057 if (token.type == '[') {
7059 add_anchor_token(']');
7060 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7061 designator->source_position = *HERE;
7062 designator->array_index = parse_expression();
7063 rem_anchor_token(']');
7065 if (designator->array_index == NULL) {
7069 last_designator->next = designator;
7070 last_designator = designator;
7082 * Parse the __builtin_offsetof() expression.
7084 static expression_t *parse_offsetof(void)
7086 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7087 expression->base.type = type_size_t;
7089 eat(T___builtin_offsetof);
7092 add_anchor_token(',');
7093 type_t *type = parse_typename();
7094 rem_anchor_token(',');
7096 add_anchor_token(')');
7097 designator_t *designator = parse_designator();
7098 rem_anchor_token(')');
7101 expression->offsetofe.type = type;
7102 expression->offsetofe.designator = designator;
7105 memset(&path, 0, sizeof(path));
7106 path.top_type = type;
7107 path.path = NEW_ARR_F(type_path_entry_t, 0);
7109 descend_into_subtype(&path);
7111 if (!walk_designator(&path, designator, true)) {
7112 return create_invalid_expression();
7115 DEL_ARR_F(path.path);
7119 return create_invalid_expression();
7123 * Parses a _builtin_va_start() expression.
7125 static expression_t *parse_va_start(void)
7127 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7129 eat(T___builtin_va_start);
7132 add_anchor_token(',');
7133 expression->va_starte.ap = parse_assignment_expression();
7134 rem_anchor_token(',');
7136 expression_t *const expr = parse_assignment_expression();
7137 if (expr->kind == EXPR_REFERENCE) {
7138 entity_t *const entity = expr->reference.entity;
7139 if (entity->base.parent_scope != ¤t_function->parameters
7140 || entity->base.next != NULL
7141 || entity->kind != ENTITY_VARIABLE) {
7142 errorf(&expr->base.source_position,
7143 "second argument of 'va_start' must be last parameter of the current function");
7145 expression->va_starte.parameter = &entity->variable;
7152 return create_invalid_expression();
7156 * Parses a _builtin_va_arg() expression.
7158 static expression_t *parse_va_arg(void)
7160 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7162 eat(T___builtin_va_arg);
7165 expression->va_arge.ap = parse_assignment_expression();
7167 expression->base.type = parse_typename();
7172 return create_invalid_expression();
7175 static expression_t *parse_builtin_symbol(void)
7177 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7179 symbol_t *symbol = token.v.symbol;
7181 expression->builtin_symbol.symbol = symbol;
7184 type_t *type = get_builtin_symbol_type(symbol);
7185 type = automatic_type_conversion(type);
7187 expression->base.type = type;
7192 * Parses a __builtin_constant() expression.
7194 static expression_t *parse_builtin_constant(void)
7196 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7198 eat(T___builtin_constant_p);
7201 add_anchor_token(')');
7202 expression->builtin_constant.value = parse_assignment_expression();
7203 rem_anchor_token(')');
7205 expression->base.type = type_int;
7209 return create_invalid_expression();
7213 * Parses a __builtin_prefetch() expression.
7215 static expression_t *parse_builtin_prefetch(void)
7217 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7219 eat(T___builtin_prefetch);
7222 add_anchor_token(')');
7223 expression->builtin_prefetch.adr = parse_assignment_expression();
7224 if (token.type == ',') {
7226 expression->builtin_prefetch.rw = parse_assignment_expression();
7228 if (token.type == ',') {
7230 expression->builtin_prefetch.locality = parse_assignment_expression();
7232 rem_anchor_token(')');
7234 expression->base.type = type_void;
7238 return create_invalid_expression();
7242 * Parses a __builtin_is_*() compare expression.
7244 static expression_t *parse_compare_builtin(void)
7246 expression_t *expression;
7248 switch (token.type) {
7249 case T___builtin_isgreater:
7250 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7252 case T___builtin_isgreaterequal:
7253 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7255 case T___builtin_isless:
7256 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7258 case T___builtin_islessequal:
7259 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7261 case T___builtin_islessgreater:
7262 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7264 case T___builtin_isunordered:
7265 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7268 internal_errorf(HERE, "invalid compare builtin found");
7270 expression->base.source_position = *HERE;
7274 expression->binary.left = parse_assignment_expression();
7276 expression->binary.right = parse_assignment_expression();
7279 type_t *const orig_type_left = expression->binary.left->base.type;
7280 type_t *const orig_type_right = expression->binary.right->base.type;
7282 type_t *const type_left = skip_typeref(orig_type_left);
7283 type_t *const type_right = skip_typeref(orig_type_right);
7284 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7285 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7286 type_error_incompatible("invalid operands in comparison",
7287 &expression->base.source_position, orig_type_left, orig_type_right);
7290 semantic_comparison(&expression->binary);
7295 return create_invalid_expression();
7300 * Parses a __builtin_expect() expression.
7302 static expression_t *parse_builtin_expect(void)
7304 expression_t *expression
7305 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7307 eat(T___builtin_expect);
7310 expression->binary.left = parse_assignment_expression();
7312 expression->binary.right = parse_constant_expression();
7315 expression->base.type = expression->binary.left->base.type;
7319 return create_invalid_expression();
7324 * Parses a MS assume() expression.
7326 static expression_t *parse_assume(void)
7328 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7333 add_anchor_token(')');
7334 expression->unary.value = parse_assignment_expression();
7335 rem_anchor_token(')');
7338 expression->base.type = type_void;
7341 return create_invalid_expression();
7345 * Return the declaration for a given label symbol or create a new one.
7347 * @param symbol the symbol of the label
7349 static label_t *get_label(symbol_t *symbol)
7352 assert(current_function != NULL);
7354 label = get_entity(symbol, NAMESPACE_LABEL);
7355 /* if we found a local label, we already created the declaration */
7356 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7357 if (label->base.parent_scope != current_scope) {
7358 assert(label->base.parent_scope->depth < current_scope->depth);
7359 current_function->goto_to_outer = true;
7361 return &label->label;
7364 label = get_entity(symbol, NAMESPACE_LABEL);
7365 /* if we found a label in the same function, then we already created the
7368 && label->base.parent_scope == ¤t_function->parameters) {
7369 return &label->label;
7372 /* otherwise we need to create a new one */
7373 label = allocate_entity_zero(ENTITY_LABEL);
7374 label->base.namespc = NAMESPACE_LABEL;
7375 label->base.symbol = symbol;
7379 return &label->label;
7383 * Parses a GNU && label address expression.
7385 static expression_t *parse_label_address(void)
7387 source_position_t source_position = token.source_position;
7389 if (token.type != T_IDENTIFIER) {
7390 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7393 symbol_t *symbol = token.v.symbol;
7396 label_t *label = get_label(symbol);
7398 label->address_taken = true;
7400 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7401 expression->base.source_position = source_position;
7403 /* label address is threaten as a void pointer */
7404 expression->base.type = type_void_ptr;
7405 expression->label_address.label = label;
7408 return create_invalid_expression();
7412 * Parse a microsoft __noop expression.
7414 static expression_t *parse_noop_expression(void)
7416 /* the result is a (int)0 */
7417 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7418 cnst->base.type = type_int;
7419 cnst->conste.v.int_value = 0;
7420 cnst->conste.is_ms_noop = true;
7424 if (token.type == '(') {
7425 /* parse arguments */
7427 add_anchor_token(')');
7428 add_anchor_token(',');
7430 if (token.type != ')') {
7432 (void)parse_assignment_expression();
7433 if (token.type != ',')
7439 rem_anchor_token(',');
7440 rem_anchor_token(')');
7448 * Parses a primary expression.
7450 static expression_t *parse_primary_expression(void)
7452 switch (token.type) {
7453 case T_false: return parse_bool_const(false);
7454 case T_true: return parse_bool_const(true);
7455 case T_INTEGER: return parse_int_const();
7456 case T_CHARACTER_CONSTANT: return parse_character_constant();
7457 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7458 case T_FLOATINGPOINT: return parse_float_const();
7459 case T_STRING_LITERAL:
7460 case T_WIDE_STRING_LITERAL: return parse_string_const();
7461 case T_IDENTIFIER: return parse_reference();
7462 case T___FUNCTION__:
7463 case T___func__: return parse_function_keyword();
7464 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7465 case T___FUNCSIG__: return parse_funcsig_keyword();
7466 case T___FUNCDNAME__: return parse_funcdname_keyword();
7467 case T___builtin_offsetof: return parse_offsetof();
7468 case T___builtin_va_start: return parse_va_start();
7469 case T___builtin_va_arg: return parse_va_arg();
7470 case T___builtin_expect:
7471 case T___builtin_alloca:
7472 case T___builtin_inf:
7473 case T___builtin_inff:
7474 case T___builtin_infl:
7475 case T___builtin_nan:
7476 case T___builtin_nanf:
7477 case T___builtin_nanl:
7478 case T___builtin_huge_val:
7479 case T___builtin_va_end: return parse_builtin_symbol();
7480 case T___builtin_isgreater:
7481 case T___builtin_isgreaterequal:
7482 case T___builtin_isless:
7483 case T___builtin_islessequal:
7484 case T___builtin_islessgreater:
7485 case T___builtin_isunordered: return parse_compare_builtin();
7486 case T___builtin_constant_p: return parse_builtin_constant();
7487 case T___builtin_prefetch: return parse_builtin_prefetch();
7488 case T__assume: return parse_assume();
7491 return parse_label_address();
7494 case '(': return parse_parenthesized_expression();
7495 case T___noop: return parse_noop_expression();
7498 errorf(HERE, "unexpected token %K, expected an expression", &token);
7499 return create_invalid_expression();
7503 * Check if the expression has the character type and issue a warning then.
7505 static void check_for_char_index_type(const expression_t *expression)
7507 type_t *const type = expression->base.type;
7508 const type_t *const base_type = skip_typeref(type);
7510 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7511 warning.char_subscripts) {
7512 warningf(&expression->base.source_position,
7513 "array subscript has type '%T'", type);
7517 static expression_t *parse_array_expression(expression_t *left)
7519 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7522 add_anchor_token(']');
7524 expression_t *inside = parse_expression();
7526 type_t *const orig_type_left = left->base.type;
7527 type_t *const orig_type_inside = inside->base.type;
7529 type_t *const type_left = skip_typeref(orig_type_left);
7530 type_t *const type_inside = skip_typeref(orig_type_inside);
7532 type_t *return_type;
7533 array_access_expression_t *array_access = &expression->array_access;
7534 if (is_type_pointer(type_left)) {
7535 return_type = type_left->pointer.points_to;
7536 array_access->array_ref = left;
7537 array_access->index = inside;
7538 check_for_char_index_type(inside);
7539 } else if (is_type_pointer(type_inside)) {
7540 return_type = type_inside->pointer.points_to;
7541 array_access->array_ref = inside;
7542 array_access->index = left;
7543 array_access->flipped = true;
7544 check_for_char_index_type(left);
7546 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7548 "array access on object with non-pointer types '%T', '%T'",
7549 orig_type_left, orig_type_inside);
7551 return_type = type_error_type;
7552 array_access->array_ref = left;
7553 array_access->index = inside;
7556 expression->base.type = automatic_type_conversion(return_type);
7558 rem_anchor_token(']');
7564 static expression_t *parse_typeprop(expression_kind_t const kind)
7566 expression_t *tp_expression = allocate_expression_zero(kind);
7567 tp_expression->base.type = type_size_t;
7569 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7571 /* we only refer to a type property, mark this case */
7572 bool old = in_type_prop;
7573 in_type_prop = true;
7576 expression_t *expression;
7577 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7579 add_anchor_token(')');
7580 orig_type = parse_typename();
7581 rem_anchor_token(')');
7584 if (token.type == '{') {
7585 /* It was not sizeof(type) after all. It is sizeof of an expression
7586 * starting with a compound literal */
7587 expression = parse_compound_literal(orig_type);
7588 goto typeprop_expression;
7591 expression = parse_sub_expression(PREC_UNARY);
7593 typeprop_expression:
7594 tp_expression->typeprop.tp_expression = expression;
7596 orig_type = revert_automatic_type_conversion(expression);
7597 expression->base.type = orig_type;
7600 tp_expression->typeprop.type = orig_type;
7601 type_t const* const type = skip_typeref(orig_type);
7602 char const* const wrong_type =
7603 is_type_incomplete(type) ? "incomplete" :
7604 type->kind == TYPE_FUNCTION ? "function designator" :
7605 type->kind == TYPE_BITFIELD ? "bitfield" :
7607 if (wrong_type != NULL) {
7608 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7609 errorf(&tp_expression->base.source_position,
7610 "operand of %s expression must not be of %s type '%T'",
7611 what, wrong_type, orig_type);
7616 return tp_expression;
7619 static expression_t *parse_sizeof(void)
7621 return parse_typeprop(EXPR_SIZEOF);
7624 static expression_t *parse_alignof(void)
7626 return parse_typeprop(EXPR_ALIGNOF);
7629 static expression_t *parse_select_expression(expression_t *compound)
7631 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7632 select->select.compound = compound;
7634 assert(token.type == '.' || token.type == T_MINUSGREATER);
7635 bool is_pointer = (token.type == T_MINUSGREATER);
7638 if (token.type != T_IDENTIFIER) {
7639 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7642 symbol_t *symbol = token.v.symbol;
7645 type_t *const orig_type = compound->base.type;
7646 type_t *const type = skip_typeref(orig_type);
7649 bool saw_error = false;
7650 if (is_type_pointer(type)) {
7653 "request for member '%Y' in something not a struct or union, but '%T'",
7657 type_left = skip_typeref(type->pointer.points_to);
7659 if (is_pointer && is_type_valid(type)) {
7660 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7667 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7668 type_left->kind == TYPE_COMPOUND_UNION) {
7669 compound_t *compound = type_left->compound.compound;
7671 if (!compound->complete) {
7672 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7674 goto create_error_entry;
7677 entry = find_compound_entry(compound, symbol);
7678 if (entry == NULL) {
7679 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7680 goto create_error_entry;
7683 if (is_type_valid(type_left) && !saw_error) {
7685 "request for member '%Y' in something not a struct or union, but '%T'",
7689 return create_invalid_expression();
7692 assert(is_declaration(entry));
7693 select->select.compound_entry = entry;
7695 type_t *entry_type = entry->declaration.type;
7697 = get_qualified_type(entry_type, type_left->base.qualifiers);
7699 /* we always do the auto-type conversions; the & and sizeof parser contains
7700 * code to revert this! */
7701 select->base.type = automatic_type_conversion(res_type);
7703 type_t *skipped = skip_typeref(res_type);
7704 if (skipped->kind == TYPE_BITFIELD) {
7705 select->base.type = skipped->bitfield.base_type;
7711 static void check_call_argument(const function_parameter_t *parameter,
7712 call_argument_t *argument, unsigned pos)
7714 type_t *expected_type = parameter->type;
7715 type_t *expected_type_skip = skip_typeref(expected_type);
7716 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7717 expression_t *arg_expr = argument->expression;
7718 type_t *arg_type = skip_typeref(arg_expr->base.type);
7720 /* handle transparent union gnu extension */
7721 if (is_type_union(expected_type_skip)
7722 && (expected_type_skip->base.modifiers
7723 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7724 compound_t *union_decl = expected_type_skip->compound.compound;
7725 type_t *best_type = NULL;
7726 entity_t *entry = union_decl->members.entities;
7727 for ( ; entry != NULL; entry = entry->base.next) {
7728 assert(is_declaration(entry));
7729 type_t *decl_type = entry->declaration.type;
7730 error = semantic_assign(decl_type, arg_expr);
7731 if (error == ASSIGN_ERROR_INCOMPATIBLE
7732 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7735 if (error == ASSIGN_SUCCESS) {
7736 best_type = decl_type;
7737 } else if (best_type == NULL) {
7738 best_type = decl_type;
7742 if (best_type != NULL) {
7743 expected_type = best_type;
7747 error = semantic_assign(expected_type, arg_expr);
7748 argument->expression = create_implicit_cast(argument->expression,
7751 if (error != ASSIGN_SUCCESS) {
7752 /* report exact scope in error messages (like "in argument 3") */
7754 snprintf(buf, sizeof(buf), "call argument %u", pos);
7755 report_assign_error(error, expected_type, arg_expr, buf,
7756 &arg_expr->base.source_position);
7757 } else if (warning.traditional || warning.conversion) {
7758 type_t *const promoted_type = get_default_promoted_type(arg_type);
7759 if (!types_compatible(expected_type_skip, promoted_type) &&
7760 !types_compatible(expected_type_skip, type_void_ptr) &&
7761 !types_compatible(type_void_ptr, promoted_type)) {
7762 /* Deliberately show the skipped types in this warning */
7763 warningf(&arg_expr->base.source_position,
7764 "passing call argument %u as '%T' rather than '%T' due to prototype",
7765 pos, expected_type_skip, promoted_type);
7771 * Parse a call expression, ie. expression '( ... )'.
7773 * @param expression the function address
7775 static expression_t *parse_call_expression(expression_t *expression)
7777 expression_t *result = allocate_expression_zero(EXPR_CALL);
7778 call_expression_t *call = &result->call;
7779 call->function = expression;
7781 type_t *const orig_type = expression->base.type;
7782 type_t *const type = skip_typeref(orig_type);
7784 function_type_t *function_type = NULL;
7785 if (is_type_pointer(type)) {
7786 type_t *const to_type = skip_typeref(type->pointer.points_to);
7788 if (is_type_function(to_type)) {
7789 function_type = &to_type->function;
7790 call->base.type = function_type->return_type;
7794 if (function_type == NULL && is_type_valid(type)) {
7795 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7798 /* parse arguments */
7800 add_anchor_token(')');
7801 add_anchor_token(',');
7803 if (token.type != ')') {
7804 call_argument_t *last_argument = NULL;
7807 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7809 argument->expression = parse_assignment_expression();
7810 if (last_argument == NULL) {
7811 call->arguments = argument;
7813 last_argument->next = argument;
7815 last_argument = argument;
7817 if (token.type != ',')
7822 rem_anchor_token(',');
7823 rem_anchor_token(')');
7826 if (function_type == NULL)
7829 function_parameter_t *parameter = function_type->parameters;
7830 call_argument_t *argument = call->arguments;
7831 if (!function_type->unspecified_parameters) {
7832 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7833 parameter = parameter->next, argument = argument->next) {
7834 check_call_argument(parameter, argument, ++pos);
7837 if (parameter != NULL) {
7838 errorf(HERE, "too few arguments to function '%E'", expression);
7839 } else if (argument != NULL && !function_type->variadic) {
7840 errorf(HERE, "too many arguments to function '%E'", expression);
7844 /* do default promotion */
7845 for (; argument != NULL; argument = argument->next) {
7846 type_t *type = argument->expression->base.type;
7848 type = get_default_promoted_type(type);
7850 argument->expression
7851 = create_implicit_cast(argument->expression, type);
7854 check_format(&result->call);
7856 if (warning.aggregate_return &&
7857 is_type_compound(skip_typeref(function_type->return_type))) {
7858 warningf(&result->base.source_position,
7859 "function call has aggregate value");
7866 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7868 static bool same_compound_type(const type_t *type1, const type_t *type2)
7871 is_type_compound(type1) &&
7872 type1->kind == type2->kind &&
7873 type1->compound.compound == type2->compound.compound;
7876 static expression_t const *get_reference_address(expression_t const *expr)
7878 bool regular_take_address = true;
7880 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7881 expr = expr->unary.value;
7883 regular_take_address = false;
7886 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7889 expr = expr->unary.value;
7892 if (expr->kind != EXPR_REFERENCE)
7895 /* special case for functions which are automatically converted to a
7896 * pointer to function without an extra TAKE_ADDRESS operation */
7897 if (!regular_take_address &&
7898 expr->reference.entity->kind != ENTITY_FUNCTION) {
7905 static void warn_reference_address_as_bool(expression_t const* expr)
7907 if (!warning.address)
7910 expr = get_reference_address(expr);
7912 warningf(&expr->base.source_position,
7913 "the address of '%Y' will always evaluate as 'true'",
7914 expr->reference.entity->base.symbol);
7919 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7921 * @param expression the conditional expression
7923 static expression_t *parse_conditional_expression(expression_t *expression)
7925 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7927 conditional_expression_t *conditional = &result->conditional;
7928 conditional->condition = expression;
7930 warn_reference_address_as_bool(expression);
7933 add_anchor_token(':');
7936 type_t *const condition_type_orig = expression->base.type;
7937 type_t *const condition_type = skip_typeref(condition_type_orig);
7938 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7939 type_error("expected a scalar type in conditional condition",
7940 &expression->base.source_position, condition_type_orig);
7943 expression_t *true_expression = expression;
7944 bool gnu_cond = false;
7945 if (GNU_MODE && token.type == ':') {
7948 true_expression = parse_expression();
7950 rem_anchor_token(':');
7952 expression_t *false_expression =
7953 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7955 type_t *const orig_true_type = true_expression->base.type;
7956 type_t *const orig_false_type = false_expression->base.type;
7957 type_t *const true_type = skip_typeref(orig_true_type);
7958 type_t *const false_type = skip_typeref(orig_false_type);
7961 type_t *result_type;
7962 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7963 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7964 /* ISO/IEC 14882:1998(E) §5.16:2 */
7965 if (true_expression->kind == EXPR_UNARY_THROW) {
7966 result_type = false_type;
7967 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7968 result_type = true_type;
7970 if (warning.other && (
7971 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7972 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7974 warningf(&conditional->base.source_position,
7975 "ISO C forbids conditional expression with only one void side");
7977 result_type = type_void;
7979 } else if (is_type_arithmetic(true_type)
7980 && is_type_arithmetic(false_type)) {
7981 result_type = semantic_arithmetic(true_type, false_type);
7983 true_expression = create_implicit_cast(true_expression, result_type);
7984 false_expression = create_implicit_cast(false_expression, result_type);
7986 conditional->true_expression = true_expression;
7987 conditional->false_expression = false_expression;
7988 conditional->base.type = result_type;
7989 } else if (same_compound_type(true_type, false_type)) {
7990 /* just take 1 of the 2 types */
7991 result_type = true_type;
7992 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7993 type_t *pointer_type;
7995 expression_t *other_expression;
7996 if (is_type_pointer(true_type) &&
7997 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7998 pointer_type = true_type;
7999 other_type = false_type;
8000 other_expression = false_expression;
8002 pointer_type = false_type;
8003 other_type = true_type;
8004 other_expression = true_expression;
8007 if (is_null_pointer_constant(other_expression)) {
8008 result_type = pointer_type;
8009 } else if (is_type_pointer(other_type)) {
8010 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8011 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8014 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8015 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8017 } else if (types_compatible(get_unqualified_type(to1),
8018 get_unqualified_type(to2))) {
8021 if (warning.other) {
8022 warningf(&conditional->base.source_position,
8023 "pointer types '%T' and '%T' in conditional expression are incompatible",
8024 true_type, false_type);
8029 type_t *const type =
8030 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8031 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8032 } else if (is_type_integer(other_type)) {
8033 if (warning.other) {
8034 warningf(&conditional->base.source_position,
8035 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8037 result_type = pointer_type;
8039 if (is_type_valid(other_type)) {
8040 type_error_incompatible("while parsing conditional",
8041 &expression->base.source_position, true_type, false_type);
8043 result_type = type_error_type;
8046 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8047 type_error_incompatible("while parsing conditional",
8048 &conditional->base.source_position, true_type,
8051 result_type = type_error_type;
8054 conditional->true_expression
8055 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8056 conditional->false_expression
8057 = create_implicit_cast(false_expression, result_type);
8058 conditional->base.type = result_type;
8061 return create_invalid_expression();
8065 * Parse an extension expression.
8067 static expression_t *parse_extension(void)
8069 eat(T___extension__);
8071 bool old_gcc_extension = in_gcc_extension;
8072 in_gcc_extension = true;
8073 expression_t *expression = parse_sub_expression(PREC_UNARY);
8074 in_gcc_extension = old_gcc_extension;
8079 * Parse a __builtin_classify_type() expression.
8081 static expression_t *parse_builtin_classify_type(void)
8083 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8084 result->base.type = type_int;
8086 eat(T___builtin_classify_type);
8089 add_anchor_token(')');
8090 expression_t *expression = parse_expression();
8091 rem_anchor_token(')');
8093 result->classify_type.type_expression = expression;
8097 return create_invalid_expression();
8101 * Parse a delete expression
8102 * ISO/IEC 14882:1998(E) §5.3.5
8104 static expression_t *parse_delete(void)
8106 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8107 result->base.type = type_void;
8111 if (token.type == '[') {
8113 result->kind = EXPR_UNARY_DELETE_ARRAY;
8118 expression_t *const value = parse_sub_expression(PREC_CAST);
8119 result->unary.value = value;
8121 type_t *const type = skip_typeref(value->base.type);
8122 if (!is_type_pointer(type)) {
8123 errorf(&value->base.source_position,
8124 "operand of delete must have pointer type");
8125 } else if (warning.other &&
8126 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8127 warningf(&value->base.source_position,
8128 "deleting 'void*' is undefined");
8135 * Parse a throw expression
8136 * ISO/IEC 14882:1998(E) §15:1
8138 static expression_t *parse_throw(void)
8140 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8141 result->base.type = type_void;
8145 expression_t *value = NULL;
8146 switch (token.type) {
8148 value = parse_assignment_expression();
8149 /* ISO/IEC 14882:1998(E) §15.1:3 */
8150 type_t *const orig_type = value->base.type;
8151 type_t *const type = skip_typeref(orig_type);
8152 if (is_type_incomplete(type)) {
8153 errorf(&value->base.source_position,
8154 "cannot throw object of incomplete type '%T'", orig_type);
8155 } else if (is_type_pointer(type)) {
8156 type_t *const points_to = skip_typeref(type->pointer.points_to);
8157 if (is_type_incomplete(points_to) &&
8158 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8159 errorf(&value->base.source_position,
8160 "cannot throw pointer to incomplete type '%T'", orig_type);
8168 result->unary.value = value;
8173 static bool check_pointer_arithmetic(const source_position_t *source_position,
8174 type_t *pointer_type,
8175 type_t *orig_pointer_type)
8177 type_t *points_to = pointer_type->pointer.points_to;
8178 points_to = skip_typeref(points_to);
8180 if (is_type_incomplete(points_to)) {
8181 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8182 errorf(source_position,
8183 "arithmetic with pointer to incomplete type '%T' not allowed",
8186 } else if (warning.pointer_arith) {
8187 warningf(source_position,
8188 "pointer of type '%T' used in arithmetic",
8191 } else if (is_type_function(points_to)) {
8193 errorf(source_position,
8194 "arithmetic with pointer to function type '%T' not allowed",
8197 } else if (warning.pointer_arith) {
8198 warningf(source_position,
8199 "pointer to a function '%T' used in arithmetic",
8206 static bool is_lvalue(const expression_t *expression)
8208 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8209 switch (expression->kind) {
8210 case EXPR_REFERENCE:
8211 case EXPR_ARRAY_ACCESS:
8213 case EXPR_UNARY_DEREFERENCE:
8217 /* Claim it is an lvalue, if the type is invalid. There was a parse
8218 * error before, which maybe prevented properly recognizing it as
8220 return !is_type_valid(skip_typeref(expression->base.type));
8224 static void semantic_incdec(unary_expression_t *expression)
8226 type_t *const orig_type = expression->value->base.type;
8227 type_t *const type = skip_typeref(orig_type);
8228 if (is_type_pointer(type)) {
8229 if (!check_pointer_arithmetic(&expression->base.source_position,
8233 } else if (!is_type_real(type) && is_type_valid(type)) {
8234 /* TODO: improve error message */
8235 errorf(&expression->base.source_position,
8236 "operation needs an arithmetic or pointer type");
8239 if (!is_lvalue(expression->value)) {
8240 /* TODO: improve error message */
8241 errorf(&expression->base.source_position, "lvalue required as operand");
8243 expression->base.type = orig_type;
8246 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8248 type_t *const orig_type = expression->value->base.type;
8249 type_t *const type = skip_typeref(orig_type);
8250 if (!is_type_arithmetic(type)) {
8251 if (is_type_valid(type)) {
8252 /* TODO: improve error message */
8253 errorf(&expression->base.source_position,
8254 "operation needs an arithmetic type");
8259 expression->base.type = orig_type;
8262 static void semantic_unexpr_plus(unary_expression_t *expression)
8264 semantic_unexpr_arithmetic(expression);
8265 if (warning.traditional)
8266 warningf(&expression->base.source_position,
8267 "traditional C rejects the unary plus operator");
8270 static void semantic_not(unary_expression_t *expression)
8272 type_t *const orig_type = expression->value->base.type;
8273 type_t *const type = skip_typeref(orig_type);
8274 if (!is_type_scalar(type) && is_type_valid(type)) {
8275 errorf(&expression->base.source_position,
8276 "operand of ! must be of scalar type");
8279 warn_reference_address_as_bool(expression->value);
8281 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8284 static void semantic_unexpr_integer(unary_expression_t *expression)
8286 type_t *const orig_type = expression->value->base.type;
8287 type_t *const type = skip_typeref(orig_type);
8288 if (!is_type_integer(type)) {
8289 if (is_type_valid(type)) {
8290 errorf(&expression->base.source_position,
8291 "operand of ~ must be of integer type");
8296 expression->base.type = orig_type;
8299 static void semantic_dereference(unary_expression_t *expression)
8301 type_t *const orig_type = expression->value->base.type;
8302 type_t *const type = skip_typeref(orig_type);
8303 if (!is_type_pointer(type)) {
8304 if (is_type_valid(type)) {
8305 errorf(&expression->base.source_position,
8306 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8311 type_t *result_type = type->pointer.points_to;
8312 result_type = automatic_type_conversion(result_type);
8313 expression->base.type = result_type;
8317 * Record that an address is taken (expression represents an lvalue).
8319 * @param expression the expression
8320 * @param may_be_register if true, the expression might be an register
8322 static void set_address_taken(expression_t *expression, bool may_be_register)
8324 if (expression->kind != EXPR_REFERENCE)
8327 entity_t *const entity = expression->reference.entity;
8329 if (entity->kind != ENTITY_VARIABLE)
8332 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8333 && !may_be_register) {
8334 errorf(&expression->base.source_position,
8335 "address of register variable '%Y' requested",
8336 entity->base.symbol);
8339 entity->variable.address_taken = true;
8343 * Check the semantic of the address taken expression.
8345 static void semantic_take_addr(unary_expression_t *expression)
8347 expression_t *value = expression->value;
8348 value->base.type = revert_automatic_type_conversion(value);
8350 type_t *orig_type = value->base.type;
8351 type_t *type = skip_typeref(orig_type);
8352 if (!is_type_valid(type))
8356 if (!is_lvalue(value)) {
8357 errorf(&expression->base.source_position, "'&' requires an lvalue");
8359 if (type->kind == TYPE_BITFIELD) {
8360 errorf(&expression->base.source_position,
8361 "'&' not allowed on object with bitfield type '%T'",
8365 set_address_taken(value, false);
8367 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8370 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8371 static expression_t *parse_##unexpression_type(void) \
8373 expression_t *unary_expression \
8374 = allocate_expression_zero(unexpression_type); \
8376 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8378 sfunc(&unary_expression->unary); \
8380 return unary_expression; \
8383 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8384 semantic_unexpr_arithmetic)
8385 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8386 semantic_unexpr_plus)
8387 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8389 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8390 semantic_dereference)
8391 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8393 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8394 semantic_unexpr_integer)
8395 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8397 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8400 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8402 static expression_t *parse_##unexpression_type(expression_t *left) \
8404 expression_t *unary_expression \
8405 = allocate_expression_zero(unexpression_type); \
8407 unary_expression->unary.value = left; \
8409 sfunc(&unary_expression->unary); \
8411 return unary_expression; \
8414 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8415 EXPR_UNARY_POSTFIX_INCREMENT,
8417 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8418 EXPR_UNARY_POSTFIX_DECREMENT,
8421 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8423 /* TODO: handle complex + imaginary types */
8425 type_left = get_unqualified_type(type_left);
8426 type_right = get_unqualified_type(type_right);
8428 /* § 6.3.1.8 Usual arithmetic conversions */
8429 if (type_left == type_long_double || type_right == type_long_double) {
8430 return type_long_double;
8431 } else if (type_left == type_double || type_right == type_double) {
8433 } else if (type_left == type_float || type_right == type_float) {
8437 type_left = promote_integer(type_left);
8438 type_right = promote_integer(type_right);
8440 if (type_left == type_right)
8443 bool const signed_left = is_type_signed(type_left);
8444 bool const signed_right = is_type_signed(type_right);
8445 int const rank_left = get_rank(type_left);
8446 int const rank_right = get_rank(type_right);
8448 if (signed_left == signed_right)
8449 return rank_left >= rank_right ? type_left : type_right;
8458 u_rank = rank_right;
8459 u_type = type_right;
8461 s_rank = rank_right;
8462 s_type = type_right;
8467 if (u_rank >= s_rank)
8470 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8472 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8473 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8477 case ATOMIC_TYPE_INT: return type_unsigned_int;
8478 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8479 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8481 default: panic("invalid atomic type");
8486 * Check the semantic restrictions for a binary expression.
8488 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8490 expression_t *const left = expression->left;
8491 expression_t *const right = expression->right;
8492 type_t *const orig_type_left = left->base.type;
8493 type_t *const orig_type_right = right->base.type;
8494 type_t *const type_left = skip_typeref(orig_type_left);
8495 type_t *const type_right = skip_typeref(orig_type_right);
8497 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8498 /* TODO: improve error message */
8499 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8500 errorf(&expression->base.source_position,
8501 "operation needs arithmetic types");
8506 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8507 expression->left = create_implicit_cast(left, arithmetic_type);
8508 expression->right = create_implicit_cast(right, arithmetic_type);
8509 expression->base.type = arithmetic_type;
8512 static void warn_div_by_zero(binary_expression_t const *const expression)
8514 if (!warning.div_by_zero ||
8515 !is_type_integer(expression->base.type))
8518 expression_t const *const right = expression->right;
8519 /* The type of the right operand can be different for /= */
8520 if (is_type_integer(right->base.type) &&
8521 is_constant_expression(right) &&
8522 fold_constant(right) == 0) {
8523 warningf(&expression->base.source_position, "division by zero");
8528 * Check the semantic restrictions for a div/mod expression.
8530 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8531 semantic_binexpr_arithmetic(expression);
8532 warn_div_by_zero(expression);
8535 static void semantic_shift_op(binary_expression_t *expression)
8537 expression_t *const left = expression->left;
8538 expression_t *const right = expression->right;
8539 type_t *const orig_type_left = left->base.type;
8540 type_t *const orig_type_right = right->base.type;
8541 type_t * type_left = skip_typeref(orig_type_left);
8542 type_t * type_right = skip_typeref(orig_type_right);
8544 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8545 /* TODO: improve error message */
8546 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8547 errorf(&expression->base.source_position,
8548 "operands of shift operation must have integer types");
8553 type_left = promote_integer(type_left);
8554 type_right = promote_integer(type_right);
8556 expression->left = create_implicit_cast(left, type_left);
8557 expression->right = create_implicit_cast(right, type_right);
8558 expression->base.type = type_left;
8561 static void semantic_add(binary_expression_t *expression)
8563 expression_t *const left = expression->left;
8564 expression_t *const right = expression->right;
8565 type_t *const orig_type_left = left->base.type;
8566 type_t *const orig_type_right = right->base.type;
8567 type_t *const type_left = skip_typeref(orig_type_left);
8568 type_t *const type_right = skip_typeref(orig_type_right);
8571 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8572 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8573 expression->left = create_implicit_cast(left, arithmetic_type);
8574 expression->right = create_implicit_cast(right, arithmetic_type);
8575 expression->base.type = arithmetic_type;
8577 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8578 check_pointer_arithmetic(&expression->base.source_position,
8579 type_left, orig_type_left);
8580 expression->base.type = type_left;
8581 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8582 check_pointer_arithmetic(&expression->base.source_position,
8583 type_right, orig_type_right);
8584 expression->base.type = type_right;
8585 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8586 errorf(&expression->base.source_position,
8587 "invalid operands to binary + ('%T', '%T')",
8588 orig_type_left, orig_type_right);
8592 static void semantic_sub(binary_expression_t *expression)
8594 expression_t *const left = expression->left;
8595 expression_t *const right = expression->right;
8596 type_t *const orig_type_left = left->base.type;
8597 type_t *const orig_type_right = right->base.type;
8598 type_t *const type_left = skip_typeref(orig_type_left);
8599 type_t *const type_right = skip_typeref(orig_type_right);
8600 source_position_t const *const pos = &expression->base.source_position;
8603 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8604 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8605 expression->left = create_implicit_cast(left, arithmetic_type);
8606 expression->right = create_implicit_cast(right, arithmetic_type);
8607 expression->base.type = arithmetic_type;
8609 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8610 check_pointer_arithmetic(&expression->base.source_position,
8611 type_left, orig_type_left);
8612 expression->base.type = type_left;
8613 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8614 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8615 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8616 if (!types_compatible(unqual_left, unqual_right)) {
8618 "subtracting pointers to incompatible types '%T' and '%T'",
8619 orig_type_left, orig_type_right);
8620 } else if (!is_type_object(unqual_left)) {
8621 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8622 errorf(pos, "subtracting pointers to non-object types '%T'",
8624 } else if (warning.other) {
8625 warningf(pos, "subtracting pointers to void");
8628 expression->base.type = type_ptrdiff_t;
8629 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8630 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8631 orig_type_left, orig_type_right);
8635 static void warn_string_literal_address(expression_t const* expr)
8637 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8638 expr = expr->unary.value;
8639 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8641 expr = expr->unary.value;
8644 if (expr->kind == EXPR_STRING_LITERAL ||
8645 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8646 warningf(&expr->base.source_position,
8647 "comparison with string literal results in unspecified behaviour");
8652 * Check the semantics of comparison expressions.
8654 * @param expression The expression to check.
8656 static void semantic_comparison(binary_expression_t *expression)
8658 expression_t *left = expression->left;
8659 expression_t *right = expression->right;
8661 if (warning.address) {
8662 warn_string_literal_address(left);
8663 warn_string_literal_address(right);
8665 expression_t const* const func_left = get_reference_address(left);
8666 if (func_left != NULL && is_null_pointer_constant(right)) {
8667 warningf(&expression->base.source_position,
8668 "the address of '%Y' will never be NULL",
8669 func_left->reference.entity->base.symbol);
8672 expression_t const* const func_right = get_reference_address(right);
8673 if (func_right != NULL && is_null_pointer_constant(right)) {
8674 warningf(&expression->base.source_position,
8675 "the address of '%Y' will never be NULL",
8676 func_right->reference.entity->base.symbol);
8680 type_t *orig_type_left = left->base.type;
8681 type_t *orig_type_right = right->base.type;
8682 type_t *type_left = skip_typeref(orig_type_left);
8683 type_t *type_right = skip_typeref(orig_type_right);
8685 /* TODO non-arithmetic types */
8686 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8687 /* test for signed vs unsigned compares */
8688 if (warning.sign_compare &&
8689 (expression->base.kind != EXPR_BINARY_EQUAL &&
8690 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8691 (is_type_signed(type_left) != is_type_signed(type_right))) {
8693 /* check if 1 of the operands is a constant, in this case we just
8694 * check wether we can safely represent the resulting constant in
8695 * the type of the other operand. */
8696 expression_t *const_expr = NULL;
8697 expression_t *other_expr = NULL;
8699 if (is_constant_expression(left)) {
8702 } else if (is_constant_expression(right)) {
8707 if (const_expr != NULL) {
8708 type_t *other_type = skip_typeref(other_expr->base.type);
8709 long val = fold_constant(const_expr);
8710 /* TODO: check if val can be represented by other_type */
8714 warningf(&expression->base.source_position,
8715 "comparison between signed and unsigned");
8717 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8718 expression->left = create_implicit_cast(left, arithmetic_type);
8719 expression->right = create_implicit_cast(right, arithmetic_type);
8720 expression->base.type = arithmetic_type;
8721 if (warning.float_equal &&
8722 (expression->base.kind == EXPR_BINARY_EQUAL ||
8723 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8724 is_type_float(arithmetic_type)) {
8725 warningf(&expression->base.source_position,
8726 "comparing floating point with == or != is unsafe");
8728 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8729 /* TODO check compatibility */
8730 } else if (is_type_pointer(type_left)) {
8731 expression->right = create_implicit_cast(right, type_left);
8732 } else if (is_type_pointer(type_right)) {
8733 expression->left = create_implicit_cast(left, type_right);
8734 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8735 type_error_incompatible("invalid operands in comparison",
8736 &expression->base.source_position,
8737 type_left, type_right);
8739 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8743 * Checks if a compound type has constant fields.
8745 static bool has_const_fields(const compound_type_t *type)
8747 compound_t *compound = type->compound;
8748 entity_t *entry = compound->members.entities;
8750 for (; entry != NULL; entry = entry->base.next) {
8751 if (!is_declaration(entry))
8754 const type_t *decl_type = skip_typeref(entry->declaration.type);
8755 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8762 static bool is_valid_assignment_lhs(expression_t const* const left)
8764 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8765 type_t *const type_left = skip_typeref(orig_type_left);
8767 if (!is_lvalue(left)) {
8768 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8773 if (is_type_array(type_left)) {
8774 errorf(HERE, "cannot assign to arrays ('%E')", left);
8777 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8778 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8782 if (is_type_incomplete(type_left)) {
8783 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8784 left, orig_type_left);
8787 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8788 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8789 left, orig_type_left);
8796 static void semantic_arithmetic_assign(binary_expression_t *expression)
8798 expression_t *left = expression->left;
8799 expression_t *right = expression->right;
8800 type_t *orig_type_left = left->base.type;
8801 type_t *orig_type_right = right->base.type;
8803 if (!is_valid_assignment_lhs(left))
8806 type_t *type_left = skip_typeref(orig_type_left);
8807 type_t *type_right = skip_typeref(orig_type_right);
8809 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8810 /* TODO: improve error message */
8811 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8812 errorf(&expression->base.source_position,
8813 "operation needs arithmetic types");
8818 /* combined instructions are tricky. We can't create an implicit cast on
8819 * the left side, because we need the uncasted form for the store.
8820 * The ast2firm pass has to know that left_type must be right_type
8821 * for the arithmetic operation and create a cast by itself */
8822 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8823 expression->right = create_implicit_cast(right, arithmetic_type);
8824 expression->base.type = type_left;
8827 static void semantic_divmod_assign(binary_expression_t *expression)
8829 semantic_arithmetic_assign(expression);
8830 warn_div_by_zero(expression);
8833 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8835 expression_t *const left = expression->left;
8836 expression_t *const right = expression->right;
8837 type_t *const orig_type_left = left->base.type;
8838 type_t *const orig_type_right = right->base.type;
8839 type_t *const type_left = skip_typeref(orig_type_left);
8840 type_t *const type_right = skip_typeref(orig_type_right);
8842 if (!is_valid_assignment_lhs(left))
8845 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8846 /* combined instructions are tricky. We can't create an implicit cast on
8847 * the left side, because we need the uncasted form for the store.
8848 * The ast2firm pass has to know that left_type must be right_type
8849 * for the arithmetic operation and create a cast by itself */
8850 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8851 expression->right = create_implicit_cast(right, arithmetic_type);
8852 expression->base.type = type_left;
8853 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8854 check_pointer_arithmetic(&expression->base.source_position,
8855 type_left, orig_type_left);
8856 expression->base.type = type_left;
8857 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8858 errorf(&expression->base.source_position,
8859 "incompatible types '%T' and '%T' in assignment",
8860 orig_type_left, orig_type_right);
8865 * Check the semantic restrictions of a logical expression.
8867 static void semantic_logical_op(binary_expression_t *expression)
8869 expression_t *const left = expression->left;
8870 expression_t *const right = expression->right;
8871 type_t *const orig_type_left = left->base.type;
8872 type_t *const orig_type_right = right->base.type;
8873 type_t *const type_left = skip_typeref(orig_type_left);
8874 type_t *const type_right = skip_typeref(orig_type_right);
8876 warn_reference_address_as_bool(left);
8877 warn_reference_address_as_bool(right);
8879 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8880 /* TODO: improve error message */
8881 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8882 errorf(&expression->base.source_position,
8883 "operation needs scalar types");
8888 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8892 * Check the semantic restrictions of a binary assign expression.
8894 static void semantic_binexpr_assign(binary_expression_t *expression)
8896 expression_t *left = expression->left;
8897 type_t *orig_type_left = left->base.type;
8899 if (!is_valid_assignment_lhs(left))
8902 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8903 report_assign_error(error, orig_type_left, expression->right,
8904 "assignment", &left->base.source_position);
8905 expression->right = create_implicit_cast(expression->right, orig_type_left);
8906 expression->base.type = orig_type_left;
8910 * Determine if the outermost operation (or parts thereof) of the given
8911 * expression has no effect in order to generate a warning about this fact.
8912 * Therefore in some cases this only examines some of the operands of the
8913 * expression (see comments in the function and examples below).
8915 * f() + 23; // warning, because + has no effect
8916 * x || f(); // no warning, because x controls execution of f()
8917 * x ? y : f(); // warning, because y has no effect
8918 * (void)x; // no warning to be able to suppress the warning
8919 * This function can NOT be used for an "expression has definitely no effect"-
8921 static bool expression_has_effect(const expression_t *const expr)
8923 switch (expr->kind) {
8924 case EXPR_UNKNOWN: break;
8925 case EXPR_INVALID: return true; /* do NOT warn */
8926 case EXPR_REFERENCE: return false;
8927 case EXPR_REFERENCE_ENUM_VALUE: return false;
8928 /* suppress the warning for microsoft __noop operations */
8929 case EXPR_CONST: return expr->conste.is_ms_noop;
8930 case EXPR_CHARACTER_CONSTANT: return false;
8931 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8932 case EXPR_STRING_LITERAL: return false;
8933 case EXPR_WIDE_STRING_LITERAL: return false;
8934 case EXPR_LABEL_ADDRESS: return false;
8937 const call_expression_t *const call = &expr->call;
8938 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8941 switch (call->function->builtin_symbol.symbol->ID) {
8942 case T___builtin_va_end: return true;
8943 default: return false;
8947 /* Generate the warning if either the left or right hand side of a
8948 * conditional expression has no effect */
8949 case EXPR_CONDITIONAL: {
8950 const conditional_expression_t *const cond = &expr->conditional;
8952 expression_has_effect(cond->true_expression) &&
8953 expression_has_effect(cond->false_expression);
8956 case EXPR_SELECT: return false;
8957 case EXPR_ARRAY_ACCESS: return false;
8958 case EXPR_SIZEOF: return false;
8959 case EXPR_CLASSIFY_TYPE: return false;
8960 case EXPR_ALIGNOF: return false;
8962 case EXPR_FUNCNAME: return false;
8963 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8964 case EXPR_BUILTIN_CONSTANT_P: return false;
8965 case EXPR_BUILTIN_PREFETCH: return true;
8966 case EXPR_OFFSETOF: return false;
8967 case EXPR_VA_START: return true;
8968 case EXPR_VA_ARG: return true;
8969 case EXPR_STATEMENT: return true; // TODO
8970 case EXPR_COMPOUND_LITERAL: return false;
8972 case EXPR_UNARY_NEGATE: return false;
8973 case EXPR_UNARY_PLUS: return false;
8974 case EXPR_UNARY_BITWISE_NEGATE: return false;
8975 case EXPR_UNARY_NOT: return false;
8976 case EXPR_UNARY_DEREFERENCE: return false;
8977 case EXPR_UNARY_TAKE_ADDRESS: return false;
8978 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8979 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8980 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8981 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8983 /* Treat void casts as if they have an effect in order to being able to
8984 * suppress the warning */
8985 case EXPR_UNARY_CAST: {
8986 type_t *const type = skip_typeref(expr->base.type);
8987 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8990 case EXPR_UNARY_CAST_IMPLICIT: return true;
8991 case EXPR_UNARY_ASSUME: return true;
8992 case EXPR_UNARY_DELETE: return true;
8993 case EXPR_UNARY_DELETE_ARRAY: return true;
8994 case EXPR_UNARY_THROW: return true;
8996 case EXPR_BINARY_ADD: return false;
8997 case EXPR_BINARY_SUB: return false;
8998 case EXPR_BINARY_MUL: return false;
8999 case EXPR_BINARY_DIV: return false;
9000 case EXPR_BINARY_MOD: return false;
9001 case EXPR_BINARY_EQUAL: return false;
9002 case EXPR_BINARY_NOTEQUAL: return false;
9003 case EXPR_BINARY_LESS: return false;
9004 case EXPR_BINARY_LESSEQUAL: return false;
9005 case EXPR_BINARY_GREATER: return false;
9006 case EXPR_BINARY_GREATEREQUAL: return false;
9007 case EXPR_BINARY_BITWISE_AND: return false;
9008 case EXPR_BINARY_BITWISE_OR: return false;
9009 case EXPR_BINARY_BITWISE_XOR: return false;
9010 case EXPR_BINARY_SHIFTLEFT: return false;
9011 case EXPR_BINARY_SHIFTRIGHT: return false;
9012 case EXPR_BINARY_ASSIGN: return true;
9013 case EXPR_BINARY_MUL_ASSIGN: return true;
9014 case EXPR_BINARY_DIV_ASSIGN: return true;
9015 case EXPR_BINARY_MOD_ASSIGN: return true;
9016 case EXPR_BINARY_ADD_ASSIGN: return true;
9017 case EXPR_BINARY_SUB_ASSIGN: return true;
9018 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9019 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9020 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9021 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9022 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9024 /* Only examine the right hand side of && and ||, because the left hand
9025 * side already has the effect of controlling the execution of the right
9027 case EXPR_BINARY_LOGICAL_AND:
9028 case EXPR_BINARY_LOGICAL_OR:
9029 /* Only examine the right hand side of a comma expression, because the left
9030 * hand side has a separate warning */
9031 case EXPR_BINARY_COMMA:
9032 return expression_has_effect(expr->binary.right);
9034 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9035 case EXPR_BINARY_ISGREATER: return false;
9036 case EXPR_BINARY_ISGREATEREQUAL: return false;
9037 case EXPR_BINARY_ISLESS: return false;
9038 case EXPR_BINARY_ISLESSEQUAL: return false;
9039 case EXPR_BINARY_ISLESSGREATER: return false;
9040 case EXPR_BINARY_ISUNORDERED: return false;
9043 internal_errorf(HERE, "unexpected expression");
9046 static void semantic_comma(binary_expression_t *expression)
9048 if (warning.unused_value) {
9049 const expression_t *const left = expression->left;
9050 if (!expression_has_effect(left)) {
9051 warningf(&left->base.source_position,
9052 "left-hand operand of comma expression has no effect");
9055 expression->base.type = expression->right->base.type;
9059 * @param prec_r precedence of the right operand
9061 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9062 static expression_t *parse_##binexpression_type(expression_t *left) \
9064 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9065 binexpr->binary.left = left; \
9068 expression_t *right = parse_sub_expression(prec_r); \
9070 binexpr->binary.right = right; \
9071 sfunc(&binexpr->binary); \
9076 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9077 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9078 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9079 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9080 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9081 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9082 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9083 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9084 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9085 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9086 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9087 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9088 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9089 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9090 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9091 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9092 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9093 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9094 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9095 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9096 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9097 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9098 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9099 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9100 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9101 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9102 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9103 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9104 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9105 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9108 static expression_t *parse_sub_expression(precedence_t precedence)
9110 if (token.type < 0) {
9111 return expected_expression_error();
9114 expression_parser_function_t *parser
9115 = &expression_parsers[token.type];
9116 source_position_t source_position = token.source_position;
9119 if (parser->parser != NULL) {
9120 left = parser->parser();
9122 left = parse_primary_expression();
9124 assert(left != NULL);
9125 left->base.source_position = source_position;
9128 if (token.type < 0) {
9129 return expected_expression_error();
9132 parser = &expression_parsers[token.type];
9133 if (parser->infix_parser == NULL)
9135 if (parser->infix_precedence < precedence)
9138 left = parser->infix_parser(left);
9140 assert(left != NULL);
9141 assert(left->kind != EXPR_UNKNOWN);
9142 left->base.source_position = source_position;
9149 * Parse an expression.
9151 static expression_t *parse_expression(void)
9153 return parse_sub_expression(PREC_EXPRESSION);
9157 * Register a parser for a prefix-like operator.
9159 * @param parser the parser function
9160 * @param token_type the token type of the prefix token
9162 static void register_expression_parser(parse_expression_function parser,
9165 expression_parser_function_t *entry = &expression_parsers[token_type];
9167 if (entry->parser != NULL) {
9168 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9169 panic("trying to register multiple expression parsers for a token");
9171 entry->parser = parser;
9175 * Register a parser for an infix operator with given precedence.
9177 * @param parser the parser function
9178 * @param token_type the token type of the infix operator
9179 * @param precedence the precedence of the operator
9181 static void register_infix_parser(parse_expression_infix_function parser,
9182 int token_type, unsigned precedence)
9184 expression_parser_function_t *entry = &expression_parsers[token_type];
9186 if (entry->infix_parser != NULL) {
9187 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9188 panic("trying to register multiple infix expression parsers for a "
9191 entry->infix_parser = parser;
9192 entry->infix_precedence = precedence;
9196 * Initialize the expression parsers.
9198 static void init_expression_parsers(void)
9200 memset(&expression_parsers, 0, sizeof(expression_parsers));
9202 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9203 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9204 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9205 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9206 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9207 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9208 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9209 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9210 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9211 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9212 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9213 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9214 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9215 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9216 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9217 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9218 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9219 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9220 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9221 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9222 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9223 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9224 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9225 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9226 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9227 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9228 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9229 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9230 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9231 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9232 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9233 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9234 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9235 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9236 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9237 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9238 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9240 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9241 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9242 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9243 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9244 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9245 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9246 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9247 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9248 register_expression_parser(parse_sizeof, T_sizeof);
9249 register_expression_parser(parse_alignof, T___alignof__);
9250 register_expression_parser(parse_extension, T___extension__);
9251 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9252 register_expression_parser(parse_delete, T_delete);
9253 register_expression_parser(parse_throw, T_throw);
9257 * Parse a asm statement arguments specification.
9259 static asm_argument_t *parse_asm_arguments(bool is_out)
9261 asm_argument_t *result = NULL;
9262 asm_argument_t **anchor = &result;
9264 while (token.type == T_STRING_LITERAL || token.type == '[') {
9265 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9266 memset(argument, 0, sizeof(argument[0]));
9268 if (token.type == '[') {
9270 if (token.type != T_IDENTIFIER) {
9271 parse_error_expected("while parsing asm argument",
9272 T_IDENTIFIER, NULL);
9275 argument->symbol = token.v.symbol;
9280 argument->constraints = parse_string_literals();
9282 add_anchor_token(')');
9283 expression_t *expression = parse_expression();
9284 rem_anchor_token(')');
9286 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9287 * change size or type representation (e.g. int -> long is ok, but
9288 * int -> float is not) */
9289 if (expression->kind == EXPR_UNARY_CAST) {
9290 type_t *const type = expression->base.type;
9291 type_kind_t const kind = type->kind;
9292 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9295 if (kind == TYPE_ATOMIC) {
9296 atomic_type_kind_t const akind = type->atomic.akind;
9297 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9298 size = get_atomic_type_size(akind);
9300 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9301 size = get_atomic_type_size(get_intptr_kind());
9305 expression_t *const value = expression->unary.value;
9306 type_t *const value_type = value->base.type;
9307 type_kind_t const value_kind = value_type->kind;
9309 unsigned value_flags;
9310 unsigned value_size;
9311 if (value_kind == TYPE_ATOMIC) {
9312 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9313 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9314 value_size = get_atomic_type_size(value_akind);
9315 } else if (value_kind == TYPE_POINTER) {
9316 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9317 value_size = get_atomic_type_size(get_intptr_kind());
9322 if (value_flags != flags || value_size != size)
9326 } while (expression->kind == EXPR_UNARY_CAST);
9330 if (!is_lvalue(expression)) {
9331 errorf(&expression->base.source_position,
9332 "asm output argument is not an lvalue");
9335 if (argument->constraints.begin[0] == '+')
9336 mark_vars_read(expression, NULL);
9338 mark_vars_read(expression, NULL);
9340 argument->expression = expression;
9343 set_address_taken(expression, true);
9346 anchor = &argument->next;
9348 if (token.type != ',')
9359 * Parse a asm statement clobber specification.
9361 static asm_clobber_t *parse_asm_clobbers(void)
9363 asm_clobber_t *result = NULL;
9364 asm_clobber_t *last = NULL;
9366 while (token.type == T_STRING_LITERAL) {
9367 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9368 clobber->clobber = parse_string_literals();
9371 last->next = clobber;
9377 if (token.type != ',')
9386 * Parse an asm statement.
9388 static statement_t *parse_asm_statement(void)
9390 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9391 asm_statement_t *asm_statement = &statement->asms;
9395 if (token.type == T_volatile) {
9397 asm_statement->is_volatile = true;
9401 add_anchor_token(')');
9402 add_anchor_token(':');
9403 asm_statement->asm_text = parse_string_literals();
9405 if (token.type != ':') {
9406 rem_anchor_token(':');
9411 asm_statement->outputs = parse_asm_arguments(true);
9412 if (token.type != ':') {
9413 rem_anchor_token(':');
9418 asm_statement->inputs = parse_asm_arguments(false);
9419 if (token.type != ':') {
9420 rem_anchor_token(':');
9423 rem_anchor_token(':');
9426 asm_statement->clobbers = parse_asm_clobbers();
9429 rem_anchor_token(')');
9433 if (asm_statement->outputs == NULL) {
9434 /* GCC: An 'asm' instruction without any output operands will be treated
9435 * identically to a volatile 'asm' instruction. */
9436 asm_statement->is_volatile = true;
9441 return create_invalid_statement();
9445 * Parse a case statement.
9447 static statement_t *parse_case_statement(void)
9449 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9450 source_position_t *const pos = &statement->base.source_position;
9454 expression_t *const expression = parse_expression();
9455 statement->case_label.expression = expression;
9456 if (!is_constant_expression(expression)) {
9457 /* This check does not prevent the error message in all cases of an
9458 * prior error while parsing the expression. At least it catches the
9459 * common case of a mistyped enum entry. */
9460 if (is_type_valid(skip_typeref(expression->base.type))) {
9461 errorf(pos, "case label does not reduce to an integer constant");
9463 statement->case_label.is_bad = true;
9465 long const val = fold_constant(expression);
9466 statement->case_label.first_case = val;
9467 statement->case_label.last_case = val;
9471 if (token.type == T_DOTDOTDOT) {
9473 expression_t *const end_range = parse_expression();
9474 statement->case_label.end_range = end_range;
9475 if (!is_constant_expression(end_range)) {
9476 /* This check does not prevent the error message in all cases of an
9477 * prior error while parsing the expression. At least it catches the
9478 * common case of a mistyped enum entry. */
9479 if (is_type_valid(skip_typeref(end_range->base.type))) {
9480 errorf(pos, "case range does not reduce to an integer constant");
9482 statement->case_label.is_bad = true;
9484 long const val = fold_constant(end_range);
9485 statement->case_label.last_case = val;
9487 if (warning.other && val < statement->case_label.first_case) {
9488 statement->case_label.is_empty_range = true;
9489 warningf(pos, "empty range specified");
9495 PUSH_PARENT(statement);
9499 if (current_switch != NULL) {
9500 if (! statement->case_label.is_bad) {
9501 /* Check for duplicate case values */
9502 case_label_statement_t *c = &statement->case_label;
9503 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9504 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9507 if (c->last_case < l->first_case || c->first_case > l->last_case)
9510 errorf(pos, "duplicate case value (previously used %P)",
9511 &l->base.source_position);
9515 /* link all cases into the switch statement */
9516 if (current_switch->last_case == NULL) {
9517 current_switch->first_case = &statement->case_label;
9519 current_switch->last_case->next = &statement->case_label;
9521 current_switch->last_case = &statement->case_label;
9523 errorf(pos, "case label not within a switch statement");
9526 statement_t *const inner_stmt = parse_statement();
9527 statement->case_label.statement = inner_stmt;
9528 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9529 errorf(&inner_stmt->base.source_position, "declaration after case label");
9536 return create_invalid_statement();
9540 * Parse a default statement.
9542 static statement_t *parse_default_statement(void)
9544 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9548 PUSH_PARENT(statement);
9551 if (current_switch != NULL) {
9552 const case_label_statement_t *def_label = current_switch->default_label;
9553 if (def_label != NULL) {
9554 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9555 &def_label->base.source_position);
9557 current_switch->default_label = &statement->case_label;
9559 /* link all cases into the switch statement */
9560 if (current_switch->last_case == NULL) {
9561 current_switch->first_case = &statement->case_label;
9563 current_switch->last_case->next = &statement->case_label;
9565 current_switch->last_case = &statement->case_label;
9568 errorf(&statement->base.source_position,
9569 "'default' label not within a switch statement");
9572 statement_t *const inner_stmt = parse_statement();
9573 statement->case_label.statement = inner_stmt;
9574 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9575 errorf(&inner_stmt->base.source_position, "declaration after default label");
9582 return create_invalid_statement();
9586 * Parse a label statement.
9588 static statement_t *parse_label_statement(void)
9590 assert(token.type == T_IDENTIFIER);
9591 symbol_t *symbol = token.v.symbol;
9592 label_t *label = get_label(symbol);
9594 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9595 statement->label.label = label;
9599 PUSH_PARENT(statement);
9601 /* if statement is already set then the label is defined twice,
9602 * otherwise it was just mentioned in a goto/local label declaration so far
9604 if (label->statement != NULL) {
9605 errorf(HERE, "duplicate label '%Y' (declared %P)",
9606 symbol, &label->base.source_position);
9608 label->base.source_position = token.source_position;
9609 label->statement = statement;
9614 if (token.type == '}') {
9615 /* TODO only warn? */
9616 if (warning.other && false) {
9617 warningf(HERE, "label at end of compound statement");
9618 statement->label.statement = create_empty_statement();
9620 errorf(HERE, "label at end of compound statement");
9621 statement->label.statement = create_invalid_statement();
9623 } else if (token.type == ';') {
9624 /* Eat an empty statement here, to avoid the warning about an empty
9625 * statement after a label. label:; is commonly used to have a label
9626 * before a closing brace. */
9627 statement->label.statement = create_empty_statement();
9630 statement_t *const inner_stmt = parse_statement();
9631 statement->label.statement = inner_stmt;
9632 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9633 errorf(&inner_stmt->base.source_position, "declaration after label");
9637 /* remember the labels in a list for later checking */
9638 *label_anchor = &statement->label;
9639 label_anchor = &statement->label.next;
9646 * Parse an if statement.
9648 static statement_t *parse_if(void)
9650 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9654 PUSH_PARENT(statement);
9656 add_anchor_token('{');
9659 add_anchor_token(')');
9660 expression_t *const expr = parse_expression();
9661 statement->ifs.condition = expr;
9662 warn_reference_address_as_bool(expr);
9663 mark_vars_read(expr, NULL);
9664 rem_anchor_token(')');
9668 rem_anchor_token('{');
9670 add_anchor_token(T_else);
9671 statement->ifs.true_statement = parse_statement();
9672 rem_anchor_token(T_else);
9674 if (token.type == T_else) {
9676 statement->ifs.false_statement = parse_statement();
9684 * Check that all enums are handled in a switch.
9686 * @param statement the switch statement to check
9688 static void check_enum_cases(const switch_statement_t *statement) {
9689 const type_t *type = skip_typeref(statement->expression->base.type);
9690 if (! is_type_enum(type))
9692 const enum_type_t *enumt = &type->enumt;
9694 /* if we have a default, no warnings */
9695 if (statement->default_label != NULL)
9698 /* FIXME: calculation of value should be done while parsing */
9699 /* TODO: quadratic algorithm here. Change to an n log n one */
9700 long last_value = -1;
9701 const entity_t *entry = enumt->enume->base.next;
9702 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9703 entry = entry->base.next) {
9704 const expression_t *expression = entry->enum_value.value;
9705 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9707 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9708 if (l->expression == NULL)
9710 if (l->first_case <= value && value <= l->last_case) {
9716 warningf(&statement->base.source_position,
9717 "enumeration value '%Y' not handled in switch",
9718 entry->base.symbol);
9725 * Parse a switch statement.
9727 static statement_t *parse_switch(void)
9729 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9733 PUSH_PARENT(statement);
9736 add_anchor_token(')');
9737 expression_t *const expr = parse_expression();
9738 mark_vars_read(expr, NULL);
9739 type_t * type = skip_typeref(expr->base.type);
9740 if (is_type_integer(type)) {
9741 type = promote_integer(type);
9742 if (warning.traditional) {
9743 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9744 warningf(&expr->base.source_position,
9745 "'%T' switch expression not converted to '%T' in ISO C",
9749 } else if (is_type_valid(type)) {
9750 errorf(&expr->base.source_position,
9751 "switch quantity is not an integer, but '%T'", type);
9752 type = type_error_type;
9754 statement->switchs.expression = create_implicit_cast(expr, type);
9756 rem_anchor_token(')');
9758 switch_statement_t *rem = current_switch;
9759 current_switch = &statement->switchs;
9760 statement->switchs.body = parse_statement();
9761 current_switch = rem;
9763 if (warning.switch_default &&
9764 statement->switchs.default_label == NULL) {
9765 warningf(&statement->base.source_position, "switch has no default case");
9767 if (warning.switch_enum)
9768 check_enum_cases(&statement->switchs);
9774 return create_invalid_statement();
9777 static statement_t *parse_loop_body(statement_t *const loop)
9779 statement_t *const rem = current_loop;
9780 current_loop = loop;
9782 statement_t *const body = parse_statement();
9788 static void check_conditon_type(expression_t const *const expr,
9789 char const *const stmt_name)
9791 type_t *const type = skip_typeref(expr->base.type);
9793 if (!is_type_scalar(type) && is_type_valid(type)) {
9794 errorf(&expr->base.source_position,
9795 "condition of %s statement must have scalar type", stmt_name);
9800 * Parse a while statement.
9802 static statement_t *parse_while(void)
9804 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9808 PUSH_PARENT(statement);
9811 add_anchor_token(')');
9812 expression_t *const cond = parse_expression();
9813 statement->whiles.condition = cond;
9814 check_conditon_type(cond, "while");
9815 warn_reference_address_as_bool(cond);
9816 mark_vars_read(cond, NULL);
9817 rem_anchor_token(')');
9820 statement->whiles.body = parse_loop_body(statement);
9826 return create_invalid_statement();
9830 * Parse a do statement.
9832 static statement_t *parse_do(void)
9834 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9838 PUSH_PARENT(statement);
9840 add_anchor_token(T_while);
9841 statement->do_while.body = parse_loop_body(statement);
9842 rem_anchor_token(T_while);
9846 add_anchor_token(')');
9847 expression_t *const cond = parse_expression();
9848 statement->do_while.condition = cond;
9849 check_conditon_type(cond, "do-while");
9850 warn_reference_address_as_bool(cond);
9851 mark_vars_read(cond, NULL);
9852 rem_anchor_token(')');
9860 return create_invalid_statement();
9864 * Parse a for statement.
9866 static statement_t *parse_for(void)
9868 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9872 PUSH_PARENT(statement);
9874 size_t const top = environment_top();
9875 scope_push(&statement->fors.scope);
9878 add_anchor_token(')');
9880 if (token.type == ';') {
9882 } else if (is_declaration_specifier(&token, false)) {
9883 parse_declaration(record_entity);
9885 add_anchor_token(';');
9886 expression_t *const init = parse_expression();
9887 statement->fors.initialisation = init;
9888 mark_vars_read(init, VAR_ANY);
9889 if (warning.unused_value && !expression_has_effect(init)) {
9890 warningf(&init->base.source_position,
9891 "initialisation of 'for'-statement has no effect");
9893 rem_anchor_token(';');
9897 if (token.type != ';') {
9898 add_anchor_token(';');
9899 expression_t *const cond = parse_expression();
9900 statement->fors.condition = cond;
9901 check_conditon_type(cond, "for");
9902 warn_reference_address_as_bool(cond);
9903 mark_vars_read(cond, NULL);
9904 rem_anchor_token(';');
9907 if (token.type != ')') {
9908 expression_t *const step = parse_expression();
9909 statement->fors.step = step;
9910 mark_vars_read(step, VAR_ANY);
9911 if (warning.unused_value && !expression_has_effect(step)) {
9912 warningf(&step->base.source_position,
9913 "step of 'for'-statement has no effect");
9917 rem_anchor_token(')');
9918 statement->fors.body = parse_loop_body(statement);
9920 assert(current_scope == &statement->fors.scope);
9922 environment_pop_to(top);
9929 rem_anchor_token(')');
9930 assert(current_scope == &statement->fors.scope);
9932 environment_pop_to(top);
9934 return create_invalid_statement();
9938 * Parse a goto statement.
9940 static statement_t *parse_goto(void)
9942 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9945 if (GNU_MODE && token.type == '*') {
9947 expression_t *expression = parse_expression();
9948 mark_vars_read(expression, NULL);
9950 /* Argh: although documentation says the expression must be of type void*,
9951 * gcc accepts anything that can be casted into void* without error */
9952 type_t *type = expression->base.type;
9954 if (type != type_error_type) {
9955 if (!is_type_pointer(type) && !is_type_integer(type)) {
9956 errorf(&expression->base.source_position,
9957 "cannot convert to a pointer type");
9958 } else if (warning.other && type != type_void_ptr) {
9959 warningf(&expression->base.source_position,
9960 "type of computed goto expression should be 'void*' not '%T'", type);
9962 expression = create_implicit_cast(expression, type_void_ptr);
9965 statement->gotos.expression = expression;
9967 if (token.type != T_IDENTIFIER) {
9969 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9971 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9975 symbol_t *symbol = token.v.symbol;
9978 statement->gotos.label = get_label(symbol);
9981 /* remember the goto's in a list for later checking */
9982 *goto_anchor = &statement->gotos;
9983 goto_anchor = &statement->gotos.next;
9989 return create_invalid_statement();
9993 * Parse a continue statement.
9995 static statement_t *parse_continue(void)
9997 if (current_loop == NULL) {
9998 errorf(HERE, "continue statement not within loop");
10001 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10011 * Parse a break statement.
10013 static statement_t *parse_break(void)
10015 if (current_switch == NULL && current_loop == NULL) {
10016 errorf(HERE, "break statement not within loop or switch");
10019 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10029 * Parse a __leave statement.
10031 static statement_t *parse_leave_statement(void)
10033 if (current_try == NULL) {
10034 errorf(HERE, "__leave statement not within __try");
10037 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10047 * Check if a given entity represents a local variable.
10049 static bool is_local_variable(const entity_t *entity)
10051 if (entity->kind != ENTITY_VARIABLE)
10054 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10055 case STORAGE_CLASS_AUTO:
10056 case STORAGE_CLASS_REGISTER: {
10057 const type_t *type = skip_typeref(entity->declaration.type);
10058 if (is_type_function(type)) {
10070 * Check if a given expression represents a local variable.
10072 static bool expression_is_local_variable(const expression_t *expression)
10074 if (expression->base.kind != EXPR_REFERENCE) {
10077 const entity_t *entity = expression->reference.entity;
10078 return is_local_variable(entity);
10082 * Check if a given expression represents a local variable and
10083 * return its declaration then, else return NULL.
10085 entity_t *expression_is_variable(const expression_t *expression)
10087 if (expression->base.kind != EXPR_REFERENCE) {
10090 entity_t *entity = expression->reference.entity;
10091 if (entity->kind != ENTITY_VARIABLE)
10098 * Parse a return statement.
10100 static statement_t *parse_return(void)
10104 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10106 expression_t *return_value = NULL;
10107 if (token.type != ';') {
10108 return_value = parse_expression();
10109 mark_vars_read(return_value, NULL);
10112 const type_t *const func_type = skip_typeref(current_function->base.type);
10113 assert(is_type_function(func_type));
10114 type_t *const return_type = skip_typeref(func_type->function.return_type);
10116 if (return_value != NULL) {
10117 type_t *return_value_type = skip_typeref(return_value->base.type);
10119 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10120 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10121 if (warning.other) {
10122 warningf(&statement->base.source_position,
10123 "'return' with a value, in function returning void");
10125 return_value = NULL;
10127 assign_error_t error = semantic_assign(return_type, return_value);
10128 report_assign_error(error, return_type, return_value, "'return'",
10129 &statement->base.source_position);
10130 return_value = create_implicit_cast(return_value, return_type);
10132 /* check for returning address of a local var */
10133 if (warning.other && return_value != NULL
10134 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10135 const expression_t *expression = return_value->unary.value;
10136 if (expression_is_local_variable(expression)) {
10137 warningf(&statement->base.source_position,
10138 "function returns address of local variable");
10141 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10142 warningf(&statement->base.source_position,
10143 "'return' without value, in function returning non-void");
10145 statement->returns.value = return_value;
10154 * Parse a declaration statement.
10156 static statement_t *parse_declaration_statement(void)
10158 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10160 entity_t *before = current_scope->last_entity;
10162 parse_external_declaration();
10164 parse_declaration(record_entity);
10166 if (before == NULL) {
10167 statement->declaration.declarations_begin = current_scope->entities;
10169 statement->declaration.declarations_begin = before->base.next;
10171 statement->declaration.declarations_end = current_scope->last_entity;
10177 * Parse an expression statement, ie. expr ';'.
10179 static statement_t *parse_expression_statement(void)
10181 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10183 expression_t *const expr = parse_expression();
10184 statement->expression.expression = expr;
10185 mark_vars_read(expr, VAR_ANY);
10194 * Parse a microsoft __try { } __finally { } or
10195 * __try{ } __except() { }
10197 static statement_t *parse_ms_try_statment(void)
10199 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10202 PUSH_PARENT(statement);
10204 ms_try_statement_t *rem = current_try;
10205 current_try = &statement->ms_try;
10206 statement->ms_try.try_statement = parse_compound_statement(false);
10211 if (token.type == T___except) {
10214 add_anchor_token(')');
10215 expression_t *const expr = parse_expression();
10216 mark_vars_read(expr, NULL);
10217 type_t * type = skip_typeref(expr->base.type);
10218 if (is_type_integer(type)) {
10219 type = promote_integer(type);
10220 } else if (is_type_valid(type)) {
10221 errorf(&expr->base.source_position,
10222 "__expect expression is not an integer, but '%T'", type);
10223 type = type_error_type;
10225 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10226 rem_anchor_token(')');
10228 statement->ms_try.final_statement = parse_compound_statement(false);
10229 } else if (token.type == T__finally) {
10231 statement->ms_try.final_statement = parse_compound_statement(false);
10233 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10234 return create_invalid_statement();
10238 return create_invalid_statement();
10241 static statement_t *parse_empty_statement(void)
10243 if (warning.empty_statement) {
10244 warningf(HERE, "statement is empty");
10246 statement_t *const statement = create_empty_statement();
10251 static statement_t *parse_local_label_declaration(void)
10253 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10257 entity_t *begin = NULL, *end = NULL;
10260 if (token.type != T_IDENTIFIER) {
10261 parse_error_expected("while parsing local label declaration",
10262 T_IDENTIFIER, NULL);
10265 symbol_t *symbol = token.v.symbol;
10266 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10267 if (entity != NULL && entity->base.parent_scope == current_scope) {
10268 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10269 symbol, &entity->base.source_position);
10271 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10273 entity->base.parent_scope = current_scope;
10274 entity->base.namespc = NAMESPACE_LABEL;
10275 entity->base.source_position = token.source_position;
10276 entity->base.symbol = symbol;
10279 end->base.next = entity;
10284 environment_push(entity);
10288 if (token.type != ',')
10294 statement->declaration.declarations_begin = begin;
10295 statement->declaration.declarations_end = end;
10299 static void parse_namespace_definition(void)
10303 entity_t *entity = NULL;
10304 symbol_t *symbol = NULL;
10306 if (token.type == T_IDENTIFIER) {
10307 symbol = token.v.symbol;
10310 entity = get_entity(symbol, NAMESPACE_NORMAL);
10311 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10312 && entity->base.parent_scope == current_scope) {
10313 error_redefined_as_different_kind(&token.source_position,
10314 entity, ENTITY_NAMESPACE);
10319 if (entity == NULL) {
10320 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10321 entity->base.symbol = symbol;
10322 entity->base.source_position = token.source_position;
10323 entity->base.namespc = NAMESPACE_NORMAL;
10324 entity->base.parent_scope = current_scope;
10327 if (token.type == '=') {
10328 /* TODO: parse namespace alias */
10329 panic("namespace alias definition not supported yet");
10332 environment_push(entity);
10333 append_entity(current_scope, entity);
10335 size_t const top = environment_top();
10336 scope_push(&entity->namespacee.members);
10343 assert(current_scope == &entity->namespacee.members);
10345 environment_pop_to(top);
10349 * Parse a statement.
10350 * There's also parse_statement() which additionally checks for
10351 * "statement has no effect" warnings
10353 static statement_t *intern_parse_statement(void)
10355 statement_t *statement = NULL;
10357 /* declaration or statement */
10358 add_anchor_token(';');
10359 switch (token.type) {
10360 case T_IDENTIFIER: {
10361 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10362 if (la1_type == ':') {
10363 statement = parse_label_statement();
10364 } else if (is_typedef_symbol(token.v.symbol)) {
10365 statement = parse_declaration_statement();
10367 /* it's an identifier, the grammar says this must be an
10368 * expression statement. However it is common that users mistype
10369 * declaration types, so we guess a bit here to improve robustness
10370 * for incorrect programs */
10371 switch (la1_type) {
10374 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10375 goto expression_statment;
10380 statement = parse_declaration_statement();
10384 expression_statment:
10385 statement = parse_expression_statement();
10392 case T___extension__:
10393 /* This can be a prefix to a declaration or an expression statement.
10394 * We simply eat it now and parse the rest with tail recursion. */
10397 } while (token.type == T___extension__);
10398 bool old_gcc_extension = in_gcc_extension;
10399 in_gcc_extension = true;
10400 statement = parse_statement();
10401 in_gcc_extension = old_gcc_extension;
10405 statement = parse_declaration_statement();
10409 statement = parse_local_label_declaration();
10412 case ';': statement = parse_empty_statement(); break;
10413 case '{': statement = parse_compound_statement(false); break;
10414 case T___leave: statement = parse_leave_statement(); break;
10415 case T___try: statement = parse_ms_try_statment(); break;
10416 case T_asm: statement = parse_asm_statement(); break;
10417 case T_break: statement = parse_break(); break;
10418 case T_case: statement = parse_case_statement(); break;
10419 case T_continue: statement = parse_continue(); break;
10420 case T_default: statement = parse_default_statement(); break;
10421 case T_do: statement = parse_do(); break;
10422 case T_for: statement = parse_for(); break;
10423 case T_goto: statement = parse_goto(); break;
10424 case T_if: statement = parse_if(); break;
10425 case T_return: statement = parse_return(); break;
10426 case T_switch: statement = parse_switch(); break;
10427 case T_while: statement = parse_while(); break;
10430 statement = parse_expression_statement();
10434 errorf(HERE, "unexpected token %K while parsing statement", &token);
10435 statement = create_invalid_statement();
10440 rem_anchor_token(';');
10442 assert(statement != NULL
10443 && statement->base.source_position.input_name != NULL);
10449 * parse a statement and emits "statement has no effect" warning if needed
10450 * (This is really a wrapper around intern_parse_statement with check for 1
10451 * single warning. It is needed, because for statement expressions we have
10452 * to avoid the warning on the last statement)
10454 static statement_t *parse_statement(void)
10456 statement_t *statement = intern_parse_statement();
10458 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10459 expression_t *expression = statement->expression.expression;
10460 if (!expression_has_effect(expression)) {
10461 warningf(&expression->base.source_position,
10462 "statement has no effect");
10470 * Parse a compound statement.
10472 static statement_t *parse_compound_statement(bool inside_expression_statement)
10474 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10476 PUSH_PARENT(statement);
10479 add_anchor_token('}');
10481 size_t const top = environment_top();
10482 scope_push(&statement->compound.scope);
10484 statement_t **anchor = &statement->compound.statements;
10485 bool only_decls_so_far = true;
10486 while (token.type != '}') {
10487 if (token.type == T_EOF) {
10488 errorf(&statement->base.source_position,
10489 "EOF while parsing compound statement");
10492 statement_t *sub_statement = intern_parse_statement();
10493 if (is_invalid_statement(sub_statement)) {
10494 /* an error occurred. if we are at an anchor, return */
10500 if (warning.declaration_after_statement) {
10501 if (sub_statement->kind != STATEMENT_DECLARATION) {
10502 only_decls_so_far = false;
10503 } else if (!only_decls_so_far) {
10504 warningf(&sub_statement->base.source_position,
10505 "ISO C90 forbids mixed declarations and code");
10509 *anchor = sub_statement;
10511 while (sub_statement->base.next != NULL)
10512 sub_statement = sub_statement->base.next;
10514 anchor = &sub_statement->base.next;
10518 /* look over all statements again to produce no effect warnings */
10519 if (warning.unused_value) {
10520 statement_t *sub_statement = statement->compound.statements;
10521 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10522 if (sub_statement->kind != STATEMENT_EXPRESSION)
10524 /* don't emit a warning for the last expression in an expression
10525 * statement as it has always an effect */
10526 if (inside_expression_statement && sub_statement->base.next == NULL)
10529 expression_t *expression = sub_statement->expression.expression;
10530 if (!expression_has_effect(expression)) {
10531 warningf(&expression->base.source_position,
10532 "statement has no effect");
10538 rem_anchor_token('}');
10539 assert(current_scope == &statement->compound.scope);
10541 environment_pop_to(top);
10548 * Check for unused global static functions and variables
10550 static void check_unused_globals(void)
10552 if (!warning.unused_function && !warning.unused_variable)
10555 for (const entity_t *entity = file_scope->entities; entity != NULL;
10556 entity = entity->base.next) {
10557 if (!is_declaration(entity))
10560 const declaration_t *declaration = &entity->declaration;
10561 if (declaration->used ||
10562 declaration->modifiers & DM_UNUSED ||
10563 declaration->modifiers & DM_USED ||
10564 declaration->storage_class != STORAGE_CLASS_STATIC)
10567 type_t *const type = declaration->type;
10569 if (entity->kind == ENTITY_FUNCTION) {
10570 /* inhibit warning for static inline functions */
10571 if (entity->function.is_inline)
10574 s = entity->function.statement != NULL ? "defined" : "declared";
10579 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10580 type, declaration->base.symbol, s);
10584 static void parse_global_asm(void)
10586 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10591 statement->asms.asm_text = parse_string_literals();
10592 statement->base.next = unit->global_asm;
10593 unit->global_asm = statement;
10601 static void parse_linkage_specification(void)
10604 assert(token.type == T_STRING_LITERAL);
10606 const char *linkage = parse_string_literals().begin;
10608 linkage_kind_t old_linkage = current_linkage;
10609 linkage_kind_t new_linkage;
10610 if (strcmp(linkage, "C") == 0) {
10611 new_linkage = LINKAGE_C;
10612 } else if (strcmp(linkage, "C++") == 0) {
10613 new_linkage = LINKAGE_CXX;
10615 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10616 new_linkage = LINKAGE_INVALID;
10618 current_linkage = new_linkage;
10620 if (token.type == '{') {
10629 assert(current_linkage == new_linkage);
10630 current_linkage = old_linkage;
10633 static void parse_external(void)
10635 switch (token.type) {
10636 DECLARATION_START_NO_EXTERN
10638 case T___extension__:
10639 case '(': /* for function declarations with implicit return type and
10640 * parenthesized declarator, i.e. (f)(void); */
10641 parse_external_declaration();
10645 if (look_ahead(1)->type == T_STRING_LITERAL) {
10646 parse_linkage_specification();
10648 parse_external_declaration();
10653 parse_global_asm();
10657 parse_namespace_definition();
10661 if (!strict_mode) {
10663 warningf(HERE, "stray ';' outside of function");
10670 errorf(HERE, "stray %K outside of function", &token);
10671 if (token.type == '(' || token.type == '{' || token.type == '[')
10672 eat_until_matching_token(token.type);
10678 static void parse_externals(void)
10680 add_anchor_token('}');
10681 add_anchor_token(T_EOF);
10684 unsigned char token_anchor_copy[T_LAST_TOKEN];
10685 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10688 while (token.type != T_EOF && token.type != '}') {
10690 bool anchor_leak = false;
10691 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10692 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10694 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10695 anchor_leak = true;
10698 if (in_gcc_extension) {
10699 errorf(HERE, "Leaked __extension__");
10700 anchor_leak = true;
10710 rem_anchor_token(T_EOF);
10711 rem_anchor_token('}');
10715 * Parse a translation unit.
10717 static void parse_translation_unit(void)
10719 add_anchor_token(T_EOF);
10724 if (token.type == T_EOF)
10727 errorf(HERE, "stray %K outside of function", &token);
10728 if (token.type == '(' || token.type == '{' || token.type == '[')
10729 eat_until_matching_token(token.type);
10737 * @return the translation unit or NULL if errors occurred.
10739 void start_parsing(void)
10741 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10742 label_stack = NEW_ARR_F(stack_entry_t, 0);
10743 diagnostic_count = 0;
10747 type_set_output(stderr);
10748 ast_set_output(stderr);
10750 assert(unit == NULL);
10751 unit = allocate_ast_zero(sizeof(unit[0]));
10753 assert(file_scope == NULL);
10754 file_scope = &unit->scope;
10756 assert(current_scope == NULL);
10757 scope_push(&unit->scope);
10760 translation_unit_t *finish_parsing(void)
10762 /* do NOT use scope_pop() here, this will crash, will it by hand */
10763 assert(current_scope == &unit->scope);
10764 current_scope = NULL;
10766 assert(file_scope == &unit->scope);
10767 check_unused_globals();
10770 DEL_ARR_F(environment_stack);
10771 DEL_ARR_F(label_stack);
10773 translation_unit_t *result = unit;
10780 lookahead_bufpos = 0;
10781 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10784 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10785 parse_translation_unit();
10789 * Initialize the parser.
10791 void init_parser(void)
10793 sym_anonymous = symbol_table_insert("<anonymous>");
10795 if (c_mode & _MS) {
10796 /* add predefined symbols for extended-decl-modifier */
10797 sym_align = symbol_table_insert("align");
10798 sym_allocate = symbol_table_insert("allocate");
10799 sym_dllimport = symbol_table_insert("dllimport");
10800 sym_dllexport = symbol_table_insert("dllexport");
10801 sym_naked = symbol_table_insert("naked");
10802 sym_noinline = symbol_table_insert("noinline");
10803 sym_noreturn = symbol_table_insert("noreturn");
10804 sym_nothrow = symbol_table_insert("nothrow");
10805 sym_novtable = symbol_table_insert("novtable");
10806 sym_property = symbol_table_insert("property");
10807 sym_get = symbol_table_insert("get");
10808 sym_put = symbol_table_insert("put");
10809 sym_selectany = symbol_table_insert("selectany");
10810 sym_thread = symbol_table_insert("thread");
10811 sym_uuid = symbol_table_insert("uuid");
10812 sym_deprecated = symbol_table_insert("deprecated");
10813 sym_restrict = symbol_table_insert("restrict");
10814 sym_noalias = symbol_table_insert("noalias");
10816 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10818 init_expression_parsers();
10819 obstack_init(&temp_obst);
10821 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10822 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10826 * Terminate the parser.
10828 void exit_parser(void)
10830 obstack_free(&temp_obst, NULL);