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)
5148 if (warning.other) {
5149 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5150 warningf(&specifiers->source_position,
5151 "useless storage class in empty declaration");
5154 type_t *type = specifiers->type;
5155 switch (type->kind) {
5156 case TYPE_COMPOUND_STRUCT:
5157 case TYPE_COMPOUND_UNION: {
5158 if (type->compound.compound->base.symbol == NULL) {
5159 warningf(&specifiers->source_position,
5160 "unnamed struct/union that defines no instances");
5169 warningf(&specifiers->source_position, "empty declaration");
5175 static void check_variable_type_complete(entity_t *ent)
5177 if (ent->kind != ENTITY_VARIABLE)
5180 declaration_t *decl = &ent->declaration;
5181 if (decl->storage_class == STORAGE_CLASS_EXTERN)
5184 type_t *type = decl->type;
5185 if (!is_type_incomplete(skip_typeref(type)))
5188 errorf(&ent->base.source_position,
5189 "variable '%#T' is of incomplete type", type, ent->base.symbol);
5193 static void parse_declaration_rest(entity_t *ndeclaration,
5194 const declaration_specifiers_t *specifiers,
5195 parsed_declaration_func finished_declaration)
5197 add_anchor_token(';');
5198 add_anchor_token(',');
5200 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5202 if (token.type == '=') {
5203 parse_init_declarator_rest(entity);
5206 check_variable_type_complete(entity);
5208 if (token.type != ',')
5212 add_anchor_token('=');
5213 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5214 rem_anchor_token('=');
5219 anonymous_entity = NULL;
5220 rem_anchor_token(';');
5221 rem_anchor_token(',');
5224 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5226 symbol_t *symbol = entity->base.symbol;
5227 if (symbol == NULL) {
5228 errorf(HERE, "anonymous declaration not valid as function parameter");
5232 assert(entity->base.namespc == NAMESPACE_NORMAL);
5233 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5234 if (previous_entity == NULL
5235 || previous_entity->base.parent_scope != current_scope) {
5236 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5241 if (is_definition) {
5242 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5245 return record_entity(entity, false);
5248 static void parse_declaration(parsed_declaration_func finished_declaration)
5250 declaration_specifiers_t specifiers;
5251 memset(&specifiers, 0, sizeof(specifiers));
5253 add_anchor_token(';');
5254 parse_declaration_specifiers(&specifiers);
5255 rem_anchor_token(';');
5257 if (token.type == ';') {
5258 parse_anonymous_declaration_rest(&specifiers);
5260 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5261 parse_declaration_rest(entity, &specifiers, finished_declaration);
5265 static type_t *get_default_promoted_type(type_t *orig_type)
5267 type_t *result = orig_type;
5269 type_t *type = skip_typeref(orig_type);
5270 if (is_type_integer(type)) {
5271 result = promote_integer(type);
5272 } else if (type == type_float) {
5273 result = type_double;
5279 static void parse_kr_declaration_list(entity_t *entity)
5281 if (entity->kind != ENTITY_FUNCTION)
5284 type_t *type = skip_typeref(entity->declaration.type);
5285 assert(is_type_function(type));
5286 if (!type->function.kr_style_parameters)
5290 add_anchor_token('{');
5292 /* push function parameters */
5293 size_t const top = environment_top();
5294 scope_push(&entity->function.parameters);
5296 entity_t *parameter = entity->function.parameters.entities;
5297 for ( ; parameter != NULL; parameter = parameter->base.next) {
5298 assert(parameter->base.parent_scope == NULL);
5299 parameter->base.parent_scope = current_scope;
5300 environment_push(parameter);
5303 /* parse declaration list */
5304 while (is_declaration_specifier(&token, false)) {
5305 parse_declaration(finished_kr_declaration);
5308 /* pop function parameters */
5309 assert(current_scope == &entity->function.parameters);
5311 environment_pop_to(top);
5313 /* update function type */
5314 type_t *new_type = duplicate_type(type);
5316 function_parameter_t *parameters = NULL;
5317 function_parameter_t *last_parameter = NULL;
5319 entity_t *parameter_declaration = entity->function.parameters.entities;
5320 for (; parameter_declaration != NULL;
5321 parameter_declaration = parameter_declaration->base.next) {
5322 type_t *parameter_type = parameter_declaration->declaration.type;
5323 if (parameter_type == NULL) {
5325 errorf(HERE, "no type specified for function parameter '%Y'",
5326 parameter_declaration->base.symbol);
5328 if (warning.implicit_int) {
5329 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5330 parameter_declaration->base.symbol);
5332 parameter_type = type_int;
5333 parameter_declaration->declaration.type = parameter_type;
5337 semantic_parameter(¶meter_declaration->declaration);
5338 parameter_type = parameter_declaration->declaration.type;
5341 * we need the default promoted types for the function type
5343 parameter_type = get_default_promoted_type(parameter_type);
5345 function_parameter_t *function_parameter
5346 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5347 memset(function_parameter, 0, sizeof(function_parameter[0]));
5349 function_parameter->type = parameter_type;
5350 if (last_parameter != NULL) {
5351 last_parameter->next = function_parameter;
5353 parameters = function_parameter;
5355 last_parameter = function_parameter;
5358 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5360 new_type->function.parameters = parameters;
5361 new_type->function.unspecified_parameters = true;
5363 type = typehash_insert(new_type);
5364 if (type != new_type) {
5365 obstack_free(type_obst, new_type);
5368 entity->declaration.type = type;
5370 rem_anchor_token('{');
5373 static bool first_err = true;
5376 * When called with first_err set, prints the name of the current function,
5379 static void print_in_function(void)
5383 diagnosticf("%s: In function '%Y':\n",
5384 current_function->base.base.source_position.input_name,
5385 current_function->base.base.symbol);
5390 * Check if all labels are defined in the current function.
5391 * Check if all labels are used in the current function.
5393 static void check_labels(void)
5395 for (const goto_statement_t *goto_statement = goto_first;
5396 goto_statement != NULL;
5397 goto_statement = goto_statement->next) {
5398 /* skip computed gotos */
5399 if (goto_statement->expression != NULL)
5402 label_t *label = goto_statement->label;
5405 if (label->base.source_position.input_name == NULL) {
5406 print_in_function();
5407 errorf(&goto_statement->base.source_position,
5408 "label '%Y' used but not defined", label->base.symbol);
5412 if (warning.unused_label) {
5413 for (const label_statement_t *label_statement = label_first;
5414 label_statement != NULL;
5415 label_statement = label_statement->next) {
5416 label_t *label = label_statement->label;
5418 if (! label->used) {
5419 print_in_function();
5420 warningf(&label_statement->base.source_position,
5421 "label '%Y' defined but not used", label->base.symbol);
5427 static void warn_unused_decl(entity_t *entity, entity_t *end,
5428 char const *const what)
5430 for (; entity != NULL; entity = entity->base.next) {
5431 if (!is_declaration(entity))
5434 declaration_t *declaration = &entity->declaration;
5435 if (declaration->implicit)
5438 if (!declaration->used) {
5439 print_in_function();
5440 warningf(&entity->base.source_position, "%s '%Y' is unused",
5441 what, entity->base.symbol);
5442 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5443 print_in_function();
5444 warningf(&entity->base.source_position, "%s '%Y' is never read",
5445 what, entity->base.symbol);
5453 static void check_unused_variables(statement_t *const stmt, void *const env)
5457 switch (stmt->kind) {
5458 case STATEMENT_DECLARATION: {
5459 declaration_statement_t const *const decls = &stmt->declaration;
5460 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5466 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5475 * Check declarations of current_function for unused entities.
5477 static void check_declarations(void)
5479 if (warning.unused_parameter) {
5480 const scope_t *scope = ¤t_function->parameters;
5482 /* do not issue unused warnings for main */
5483 if (!is_sym_main(current_function->base.base.symbol)) {
5484 warn_unused_decl(scope->entities, NULL, "parameter");
5487 if (warning.unused_variable) {
5488 walk_statements(current_function->statement, check_unused_variables,
5493 static int determine_truth(expression_t const* const cond)
5496 !is_constant_expression(cond) ? 0 :
5497 fold_constant(cond) != 0 ? 1 :
5501 static bool expression_returns(expression_t const *const expr)
5503 switch (expr->kind) {
5505 expression_t const *const func = expr->call.function;
5506 if (func->kind == EXPR_REFERENCE) {
5507 entity_t *entity = func->reference.entity;
5508 if (entity->kind == ENTITY_FUNCTION
5509 && entity->declaration.modifiers & DM_NORETURN)
5513 if (!expression_returns(func))
5516 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5517 if (!expression_returns(arg->expression))
5524 case EXPR_REFERENCE:
5525 case EXPR_REFERENCE_ENUM_VALUE:
5527 case EXPR_CHARACTER_CONSTANT:
5528 case EXPR_WIDE_CHARACTER_CONSTANT:
5529 case EXPR_STRING_LITERAL:
5530 case EXPR_WIDE_STRING_LITERAL:
5531 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5532 case EXPR_LABEL_ADDRESS:
5533 case EXPR_CLASSIFY_TYPE:
5534 case EXPR_SIZEOF: // TODO handle obscure VLA case
5537 case EXPR_BUILTIN_SYMBOL:
5538 case EXPR_BUILTIN_CONSTANT_P:
5539 case EXPR_BUILTIN_PREFETCH:
5542 case EXPR_STATEMENT: // TODO implement
5545 case EXPR_CONDITIONAL:
5546 // TODO handle constant expression
5548 expression_returns(expr->conditional.condition) && (
5549 expression_returns(expr->conditional.true_expression) ||
5550 expression_returns(expr->conditional.false_expression)
5554 return expression_returns(expr->select.compound);
5556 case EXPR_ARRAY_ACCESS:
5558 expression_returns(expr->array_access.array_ref) &&
5559 expression_returns(expr->array_access.index);
5562 return expression_returns(expr->va_starte.ap);
5565 return expression_returns(expr->va_arge.ap);
5567 EXPR_UNARY_CASES_MANDATORY
5568 return expression_returns(expr->unary.value);
5570 case EXPR_UNARY_THROW:
5574 // TODO handle constant lhs of && and ||
5576 expression_returns(expr->binary.left) &&
5577 expression_returns(expr->binary.right);
5583 panic("unhandled expression");
5586 static bool noreturn_candidate;
5588 static void check_reachable(statement_t *const stmt)
5590 if (stmt->base.reachable)
5592 if (stmt->kind != STATEMENT_DO_WHILE)
5593 stmt->base.reachable = true;
5595 statement_t *last = stmt;
5597 switch (stmt->kind) {
5598 case STATEMENT_INVALID:
5599 case STATEMENT_EMPTY:
5600 case STATEMENT_DECLARATION:
5601 case STATEMENT_LOCAL_LABEL:
5603 next = stmt->base.next;
5606 case STATEMENT_COMPOUND:
5607 next = stmt->compound.statements;
5610 case STATEMENT_RETURN:
5611 noreturn_candidate = false;
5614 case STATEMENT_IF: {
5615 if_statement_t const* const ifs = &stmt->ifs;
5616 int const val = determine_truth(ifs->condition);
5619 check_reachable(ifs->true_statement);
5624 if (ifs->false_statement != NULL) {
5625 check_reachable(ifs->false_statement);
5629 next = stmt->base.next;
5633 case STATEMENT_SWITCH: {
5634 switch_statement_t const *const switchs = &stmt->switchs;
5635 expression_t const *const expr = switchs->expression;
5637 if (is_constant_expression(expr)) {
5638 long const val = fold_constant(expr);
5639 case_label_statement_t * defaults = NULL;
5640 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5641 if (i->expression == NULL) {
5646 if (i->first_case <= val && val <= i->last_case) {
5647 check_reachable((statement_t*)i);
5652 if (defaults != NULL) {
5653 check_reachable((statement_t*)defaults);
5657 bool has_default = false;
5658 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5659 if (i->expression == NULL)
5662 check_reachable((statement_t*)i);
5669 next = stmt->base.next;
5673 case STATEMENT_EXPRESSION: {
5674 /* Check for noreturn function call */
5675 expression_t const *const expr = stmt->expression.expression;
5676 if (!expression_returns(expr))
5679 next = stmt->base.next;
5683 case STATEMENT_CONTINUE: {
5684 statement_t *parent = stmt;
5686 parent = parent->base.parent;
5687 if (parent == NULL) /* continue not within loop */
5691 switch (parent->kind) {
5692 case STATEMENT_WHILE: goto continue_while;
5693 case STATEMENT_DO_WHILE: goto continue_do_while;
5694 case STATEMENT_FOR: goto continue_for;
5701 case STATEMENT_BREAK: {
5702 statement_t *parent = stmt;
5704 parent = parent->base.parent;
5705 if (parent == NULL) /* break not within loop/switch */
5708 switch (parent->kind) {
5709 case STATEMENT_SWITCH:
5710 case STATEMENT_WHILE:
5711 case STATEMENT_DO_WHILE:
5714 next = parent->base.next;
5715 goto found_break_parent;
5724 case STATEMENT_GOTO:
5725 if (stmt->gotos.expression) {
5726 statement_t *parent = stmt->base.parent;
5727 if (parent == NULL) /* top level goto */
5731 next = stmt->gotos.label->statement;
5732 if (next == NULL) /* missing label */
5737 case STATEMENT_LABEL:
5738 next = stmt->label.statement;
5741 case STATEMENT_CASE_LABEL:
5742 next = stmt->case_label.statement;
5745 case STATEMENT_WHILE: {
5746 while_statement_t const *const whiles = &stmt->whiles;
5747 int const val = determine_truth(whiles->condition);
5750 check_reachable(whiles->body);
5755 next = stmt->base.next;
5759 case STATEMENT_DO_WHILE:
5760 next = stmt->do_while.body;
5763 case STATEMENT_FOR: {
5764 for_statement_t *const fors = &stmt->fors;
5766 if (fors->condition_reachable)
5768 fors->condition_reachable = true;
5770 expression_t const *const cond = fors->condition;
5772 cond == NULL ? 1 : determine_truth(cond);
5775 check_reachable(fors->body);
5780 next = stmt->base.next;
5784 case STATEMENT_MS_TRY: {
5785 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5786 check_reachable(ms_try->try_statement);
5787 next = ms_try->final_statement;
5791 case STATEMENT_LEAVE: {
5792 statement_t *parent = stmt;
5794 parent = parent->base.parent;
5795 if (parent == NULL) /* __leave not within __try */
5798 if (parent->kind == STATEMENT_MS_TRY) {
5800 next = parent->ms_try.final_statement;
5808 while (next == NULL) {
5809 next = last->base.parent;
5811 noreturn_candidate = false;
5813 type_t *const type = current_function->base.type;
5814 assert(is_type_function(type));
5815 type_t *const ret = skip_typeref(type->function.return_type);
5816 if (warning.return_type &&
5817 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5818 is_type_valid(ret) &&
5819 !is_sym_main(current_function->base.base.symbol)) {
5820 warningf(&stmt->base.source_position,
5821 "control reaches end of non-void function");
5826 switch (next->kind) {
5827 case STATEMENT_INVALID:
5828 case STATEMENT_EMPTY:
5829 case STATEMENT_DECLARATION:
5830 case STATEMENT_LOCAL_LABEL:
5831 case STATEMENT_EXPRESSION:
5833 case STATEMENT_RETURN:
5834 case STATEMENT_CONTINUE:
5835 case STATEMENT_BREAK:
5836 case STATEMENT_GOTO:
5837 case STATEMENT_LEAVE:
5838 panic("invalid control flow in function");
5840 case STATEMENT_COMPOUND:
5842 case STATEMENT_SWITCH:
5843 case STATEMENT_LABEL:
5844 case STATEMENT_CASE_LABEL:
5846 next = next->base.next;
5849 case STATEMENT_WHILE: {
5851 if (next->base.reachable)
5853 next->base.reachable = true;
5855 while_statement_t const *const whiles = &next->whiles;
5856 int const val = determine_truth(whiles->condition);
5859 check_reachable(whiles->body);
5865 next = next->base.next;
5869 case STATEMENT_DO_WHILE: {
5871 if (next->base.reachable)
5873 next->base.reachable = true;
5875 do_while_statement_t const *const dw = &next->do_while;
5876 int const val = determine_truth(dw->condition);
5879 check_reachable(dw->body);
5885 next = next->base.next;
5889 case STATEMENT_FOR: {
5891 for_statement_t *const fors = &next->fors;
5893 fors->step_reachable = true;
5895 if (fors->condition_reachable)
5897 fors->condition_reachable = true;
5899 expression_t const *const cond = fors->condition;
5901 cond == NULL ? 1 : determine_truth(cond);
5904 check_reachable(fors->body);
5910 next = next->base.next;
5914 case STATEMENT_MS_TRY:
5916 next = next->ms_try.final_statement;
5921 check_reachable(next);
5924 static void check_unreachable(statement_t* const stmt, void *const env)
5928 switch (stmt->kind) {
5929 case STATEMENT_DO_WHILE:
5930 if (!stmt->base.reachable) {
5931 expression_t const *const cond = stmt->do_while.condition;
5932 if (determine_truth(cond) >= 0) {
5933 warningf(&cond->base.source_position,
5934 "condition of do-while-loop is unreachable");
5939 case STATEMENT_FOR: {
5940 for_statement_t const* const fors = &stmt->fors;
5942 // if init and step are unreachable, cond is unreachable, too
5943 if (!stmt->base.reachable && !fors->step_reachable) {
5944 warningf(&stmt->base.source_position, "statement is unreachable");
5946 if (!stmt->base.reachable && fors->initialisation != NULL) {
5947 warningf(&fors->initialisation->base.source_position,
5948 "initialisation of for-statement is unreachable");
5951 if (!fors->condition_reachable && fors->condition != NULL) {
5952 warningf(&fors->condition->base.source_position,
5953 "condition of for-statement is unreachable");
5956 if (!fors->step_reachable && fors->step != NULL) {
5957 warningf(&fors->step->base.source_position,
5958 "step of for-statement is unreachable");
5964 case STATEMENT_COMPOUND:
5965 if (stmt->compound.statements != NULL)
5970 if (!stmt->base.reachable)
5971 warningf(&stmt->base.source_position, "statement is unreachable");
5976 static void parse_external_declaration(void)
5978 /* function-definitions and declarations both start with declaration
5980 declaration_specifiers_t specifiers;
5981 memset(&specifiers, 0, sizeof(specifiers));
5983 add_anchor_token(';');
5984 parse_declaration_specifiers(&specifiers);
5985 rem_anchor_token(';');
5987 /* must be a declaration */
5988 if (token.type == ';') {
5989 parse_anonymous_declaration_rest(&specifiers);
5993 add_anchor_token(',');
5994 add_anchor_token('=');
5995 add_anchor_token(';');
5996 add_anchor_token('{');
5998 /* declarator is common to both function-definitions and declarations */
5999 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
6001 rem_anchor_token('{');
6002 rem_anchor_token(';');
6003 rem_anchor_token('=');
6004 rem_anchor_token(',');
6006 /* must be a declaration */
6007 switch (token.type) {
6011 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6015 /* must be a function definition */
6016 parse_kr_declaration_list(ndeclaration);
6018 if (token.type != '{') {
6019 parse_error_expected("while parsing function definition", '{', NULL);
6020 eat_until_matching_token(';');
6024 assert(is_declaration(ndeclaration));
6025 type_t *type = skip_typeref(ndeclaration->declaration.type);
6027 if (!is_type_function(type)) {
6028 if (is_type_valid(type)) {
6029 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6030 type, ndeclaration->base.symbol);
6036 if (warning.aggregate_return &&
6037 is_type_compound(skip_typeref(type->function.return_type))) {
6038 warningf(HERE, "function '%Y' returns an aggregate",
6039 ndeclaration->base.symbol);
6041 if (warning.traditional && !type->function.unspecified_parameters) {
6042 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6043 ndeclaration->base.symbol);
6045 if (warning.old_style_definition && type->function.unspecified_parameters) {
6046 warningf(HERE, "old-style function definition '%Y'",
6047 ndeclaration->base.symbol);
6050 /* § 6.7.5.3 (14) a function definition with () means no
6051 * parameters (and not unspecified parameters) */
6052 if (type->function.unspecified_parameters
6053 && type->function.parameters == NULL
6054 && !type->function.kr_style_parameters) {
6055 type_t *duplicate = duplicate_type(type);
6056 duplicate->function.unspecified_parameters = false;
6058 type = typehash_insert(duplicate);
6059 if (type != duplicate) {
6060 obstack_free(type_obst, duplicate);
6062 ndeclaration->declaration.type = type;
6065 entity_t *const entity = record_entity(ndeclaration, true);
6066 assert(entity->kind == ENTITY_FUNCTION);
6067 assert(ndeclaration->kind == ENTITY_FUNCTION);
6069 function_t *function = &entity->function;
6070 if (ndeclaration != entity) {
6071 function->parameters = ndeclaration->function.parameters;
6073 assert(is_declaration(entity));
6074 type = skip_typeref(entity->declaration.type);
6076 /* push function parameters and switch scope */
6077 size_t const top = environment_top();
6078 scope_push(&function->parameters);
6080 entity_t *parameter = function->parameters.entities;
6081 for (; parameter != NULL; parameter = parameter->base.next) {
6082 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6083 parameter->base.parent_scope = current_scope;
6085 assert(parameter->base.parent_scope == NULL
6086 || parameter->base.parent_scope == current_scope);
6087 parameter->base.parent_scope = current_scope;
6088 if (parameter->base.symbol == NULL) {
6089 errorf(¶meter->base.source_position, "parameter name omitted");
6092 environment_push(parameter);
6095 if (function->statement != NULL) {
6096 parser_error_multiple_definition(entity, HERE);
6099 /* parse function body */
6100 int label_stack_top = label_top();
6101 function_t *old_current_function = current_function;
6102 current_function = function;
6103 current_parent = NULL;
6106 goto_anchor = &goto_first;
6108 label_anchor = &label_first;
6110 statement_t *const body = parse_compound_statement(false);
6111 function->statement = body;
6114 check_declarations();
6115 if (warning.return_type ||
6116 warning.unreachable_code ||
6117 (warning.missing_noreturn
6118 && !(function->base.modifiers & DM_NORETURN))) {
6119 noreturn_candidate = true;
6120 check_reachable(body);
6121 if (warning.unreachable_code)
6122 walk_statements(body, check_unreachable, NULL);
6123 if (warning.missing_noreturn &&
6124 noreturn_candidate &&
6125 !(function->base.modifiers & DM_NORETURN)) {
6126 warningf(&body->base.source_position,
6127 "function '%#T' is candidate for attribute 'noreturn'",
6128 type, entity->base.symbol);
6132 assert(current_parent == NULL);
6133 assert(current_function == function);
6134 current_function = old_current_function;
6135 label_pop_to(label_stack_top);
6138 assert(current_scope == &function->parameters);
6140 environment_pop_to(top);
6143 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6144 source_position_t *source_position,
6145 const symbol_t *symbol)
6147 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6149 type->bitfield.base_type = base_type;
6150 type->bitfield.size_expression = size;
6153 type_t *skipped_type = skip_typeref(base_type);
6154 if (!is_type_integer(skipped_type)) {
6155 errorf(HERE, "bitfield base type '%T' is not an integer type",
6159 bit_size = skipped_type->base.size * 8;
6162 if (is_constant_expression(size)) {
6163 long v = fold_constant(size);
6166 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6167 } else if (v == 0) {
6168 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6169 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6170 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6172 type->bitfield.bit_size = v;
6179 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6181 entity_t *iter = compound->members.entities;
6182 for (; iter != NULL; iter = iter->base.next) {
6183 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6186 if (iter->base.symbol == symbol) {
6188 } else if (iter->base.symbol == NULL) {
6189 type_t *type = skip_typeref(iter->declaration.type);
6190 if (is_type_compound(type)) {
6192 = find_compound_entry(type->compound.compound, symbol);
6203 static void parse_compound_declarators(compound_t *compound,
6204 const declaration_specifiers_t *specifiers)
6209 if (token.type == ':') {
6210 source_position_t source_position = *HERE;
6213 type_t *base_type = specifiers->type;
6214 expression_t *size = parse_constant_expression();
6216 type_t *type = make_bitfield_type(base_type, size,
6217 &source_position, sym_anonymous);
6219 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6220 entity->base.namespc = NAMESPACE_NORMAL;
6221 entity->base.source_position = source_position;
6222 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6223 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6224 entity->declaration.modifiers = specifiers->modifiers;
6225 entity->declaration.type = type;
6227 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6228 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6230 if (token.type == ':') {
6231 source_position_t source_position = *HERE;
6233 expression_t *size = parse_constant_expression();
6235 type_t *type = entity->declaration.type;
6236 type_t *bitfield_type = make_bitfield_type(type, size,
6237 &source_position, entity->base.symbol);
6238 entity->declaration.type = bitfield_type;
6242 /* make sure we don't define a symbol multiple times */
6243 symbol_t *symbol = entity->base.symbol;
6244 if (symbol != NULL) {
6245 entity_t *prev = find_compound_entry(compound, symbol);
6248 errorf(&entity->base.source_position,
6249 "multiple declarations of symbol '%Y' (declared %P)",
6250 symbol, &prev->base.source_position);
6254 append_entity(&compound->members, entity);
6256 type_t *orig_type = entity->declaration.type;
6257 type_t *type = skip_typeref(orig_type);
6258 if (is_type_function(type)) {
6259 errorf(&entity->base.source_position,
6260 "compound member '%Y' must not have function type '%T'",
6261 entity->base.symbol, orig_type);
6262 } else if (is_type_incomplete(type)) {
6263 /* §6.7.2.1:16 flexible array member */
6264 if (is_type_array(type) &&
6265 token.type == ';' &&
6266 look_ahead(1)->type == '}') {
6267 compound->has_flexible_member = true;
6269 errorf(&entity->base.source_position,
6270 "compound member '%Y' has incomplete type '%T'",
6271 entity->base.symbol, orig_type);
6275 if (token.type != ',')
6282 anonymous_entity = NULL;
6285 static void parse_compound_type_entries(compound_t *compound)
6288 add_anchor_token('}');
6290 while (token.type != '}') {
6291 if (token.type == T_EOF) {
6292 errorf(HERE, "EOF while parsing struct");
6295 declaration_specifiers_t specifiers;
6296 memset(&specifiers, 0, sizeof(specifiers));
6297 parse_declaration_specifiers(&specifiers);
6299 parse_compound_declarators(compound, &specifiers);
6301 rem_anchor_token('}');
6305 compound->complete = true;
6308 static type_t *parse_typename(void)
6310 declaration_specifiers_t specifiers;
6311 memset(&specifiers, 0, sizeof(specifiers));
6312 parse_declaration_specifiers(&specifiers);
6313 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6314 /* TODO: improve error message, user does probably not know what a
6315 * storage class is...
6317 errorf(HERE, "typename may not have a storage class");
6320 type_t *result = parse_abstract_declarator(specifiers.type);
6328 typedef expression_t* (*parse_expression_function)(void);
6329 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6331 typedef struct expression_parser_function_t expression_parser_function_t;
6332 struct expression_parser_function_t {
6333 parse_expression_function parser;
6334 unsigned infix_precedence;
6335 parse_expression_infix_function infix_parser;
6338 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6341 * Prints an error message if an expression was expected but not read
6343 static expression_t *expected_expression_error(void)
6345 /* skip the error message if the error token was read */
6346 if (token.type != T_ERROR) {
6347 errorf(HERE, "expected expression, got token '%K'", &token);
6351 return create_invalid_expression();
6355 * Parse a string constant.
6357 static expression_t *parse_string_const(void)
6360 if (token.type == T_STRING_LITERAL) {
6361 string_t res = token.v.string;
6363 while (token.type == T_STRING_LITERAL) {
6364 res = concat_strings(&res, &token.v.string);
6367 if (token.type != T_WIDE_STRING_LITERAL) {
6368 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6369 /* note: that we use type_char_ptr here, which is already the
6370 * automatic converted type. revert_automatic_type_conversion
6371 * will construct the array type */
6372 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6373 cnst->string.value = res;
6377 wres = concat_string_wide_string(&res, &token.v.wide_string);
6379 wres = token.v.wide_string;
6384 switch (token.type) {
6385 case T_WIDE_STRING_LITERAL:
6386 wres = concat_wide_strings(&wres, &token.v.wide_string);
6389 case T_STRING_LITERAL:
6390 wres = concat_wide_string_string(&wres, &token.v.string);
6394 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6395 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6396 cnst->wide_string.value = wres;
6405 * Parse a boolean constant.
6407 static expression_t *parse_bool_const(bool value)
6409 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6410 cnst->base.type = type_bool;
6411 cnst->conste.v.int_value = value;
6419 * Parse an integer constant.
6421 static expression_t *parse_int_const(void)
6423 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6424 cnst->base.type = token.datatype;
6425 cnst->conste.v.int_value = token.v.intvalue;
6433 * Parse a character constant.
6435 static expression_t *parse_character_constant(void)
6437 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6438 cnst->base.type = token.datatype;
6439 cnst->conste.v.character = token.v.string;
6441 if (cnst->conste.v.character.size != 1) {
6443 errorf(HERE, "more than 1 character in character constant");
6444 } else if (warning.multichar) {
6445 warningf(HERE, "multi-character character constant");
6454 * Parse a wide character constant.
6456 static expression_t *parse_wide_character_constant(void)
6458 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6459 cnst->base.type = token.datatype;
6460 cnst->conste.v.wide_character = token.v.wide_string;
6462 if (cnst->conste.v.wide_character.size != 1) {
6464 errorf(HERE, "more than 1 character in character constant");
6465 } else if (warning.multichar) {
6466 warningf(HERE, "multi-character character constant");
6475 * Parse a float constant.
6477 static expression_t *parse_float_const(void)
6479 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6480 cnst->base.type = token.datatype;
6481 cnst->conste.v.float_value = token.v.floatvalue;
6488 static entity_t *create_implicit_function(symbol_t *symbol,
6489 const source_position_t *source_position)
6491 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6492 ntype->function.return_type = type_int;
6493 ntype->function.unspecified_parameters = true;
6495 type_t *type = typehash_insert(ntype);
6496 if (type != ntype) {
6500 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6501 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6502 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6503 entity->declaration.type = type;
6504 entity->declaration.implicit = true;
6505 entity->base.symbol = symbol;
6506 entity->base.source_position = *source_position;
6508 bool strict_prototypes_old = warning.strict_prototypes;
6509 warning.strict_prototypes = false;
6510 record_entity(entity, false);
6511 warning.strict_prototypes = strict_prototypes_old;
6517 * Creates a return_type (func)(argument_type) function type if not
6520 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6521 type_t *argument_type2)
6523 function_parameter_t *parameter2
6524 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6525 memset(parameter2, 0, sizeof(parameter2[0]));
6526 parameter2->type = argument_type2;
6528 function_parameter_t *parameter1
6529 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6530 memset(parameter1, 0, sizeof(parameter1[0]));
6531 parameter1->type = argument_type1;
6532 parameter1->next = parameter2;
6534 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6535 type->function.return_type = return_type;
6536 type->function.parameters = parameter1;
6538 type_t *result = typehash_insert(type);
6539 if (result != type) {
6547 * Creates a return_type (func)(argument_type) function type if not
6550 * @param return_type the return type
6551 * @param argument_type the argument type
6553 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6555 function_parameter_t *parameter
6556 = obstack_alloc(type_obst, sizeof(parameter[0]));
6557 memset(parameter, 0, sizeof(parameter[0]));
6558 parameter->type = argument_type;
6560 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6561 type->function.return_type = return_type;
6562 type->function.parameters = parameter;
6564 type_t *result = typehash_insert(type);
6565 if (result != type) {
6572 static type_t *make_function_0_type(type_t *return_type)
6574 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6575 type->function.return_type = return_type;
6576 type->function.parameters = NULL;
6578 type_t *result = typehash_insert(type);
6579 if (result != type) {
6587 * Creates a function type for some function like builtins.
6589 * @param symbol the symbol describing the builtin
6591 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6593 switch (symbol->ID) {
6594 case T___builtin_alloca:
6595 return make_function_1_type(type_void_ptr, type_size_t);
6596 case T___builtin_huge_val:
6597 return make_function_0_type(type_double);
6598 case T___builtin_inf:
6599 return make_function_0_type(type_double);
6600 case T___builtin_inff:
6601 return make_function_0_type(type_float);
6602 case T___builtin_infl:
6603 return make_function_0_type(type_long_double);
6604 case T___builtin_nan:
6605 return make_function_1_type(type_double, type_char_ptr);
6606 case T___builtin_nanf:
6607 return make_function_1_type(type_float, type_char_ptr);
6608 case T___builtin_nanl:
6609 return make_function_1_type(type_long_double, type_char_ptr);
6610 case T___builtin_va_end:
6611 return make_function_1_type(type_void, type_valist);
6612 case T___builtin_expect:
6613 return make_function_2_type(type_long, type_long, type_long);
6615 internal_errorf(HERE, "not implemented builtin symbol found");
6620 * Performs automatic type cast as described in § 6.3.2.1.
6622 * @param orig_type the original type
6624 static type_t *automatic_type_conversion(type_t *orig_type)
6626 type_t *type = skip_typeref(orig_type);
6627 if (is_type_array(type)) {
6628 array_type_t *array_type = &type->array;
6629 type_t *element_type = array_type->element_type;
6630 unsigned qualifiers = array_type->base.qualifiers;
6632 return make_pointer_type(element_type, qualifiers);
6635 if (is_type_function(type)) {
6636 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6643 * reverts the automatic casts of array to pointer types and function
6644 * to function-pointer types as defined § 6.3.2.1
6646 type_t *revert_automatic_type_conversion(const expression_t *expression)
6648 switch (expression->kind) {
6649 case EXPR_REFERENCE: {
6650 entity_t *entity = expression->reference.entity;
6651 if (is_declaration(entity)) {
6652 return entity->declaration.type;
6653 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6654 return entity->enum_value.enum_type;
6656 panic("no declaration or enum in reference");
6661 entity_t *entity = expression->select.compound_entry;
6662 assert(is_declaration(entity));
6663 type_t *type = entity->declaration.type;
6664 return get_qualified_type(type,
6665 expression->base.type->base.qualifiers);
6668 case EXPR_UNARY_DEREFERENCE: {
6669 const expression_t *const value = expression->unary.value;
6670 type_t *const type = skip_typeref(value->base.type);
6671 assert(is_type_pointer(type));
6672 return type->pointer.points_to;
6675 case EXPR_BUILTIN_SYMBOL:
6676 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6678 case EXPR_ARRAY_ACCESS: {
6679 const expression_t *array_ref = expression->array_access.array_ref;
6680 type_t *type_left = skip_typeref(array_ref->base.type);
6681 if (!is_type_valid(type_left))
6683 assert(is_type_pointer(type_left));
6684 return type_left->pointer.points_to;
6687 case EXPR_STRING_LITERAL: {
6688 size_t size = expression->string.value.size;
6689 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6692 case EXPR_WIDE_STRING_LITERAL: {
6693 size_t size = expression->wide_string.value.size;
6694 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6697 case EXPR_COMPOUND_LITERAL:
6698 return expression->compound_literal.type;
6703 return expression->base.type;
6706 static expression_t *parse_reference(void)
6708 symbol_t *const symbol = token.v.symbol;
6710 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6712 if (entity == NULL) {
6713 if (!strict_mode && look_ahead(1)->type == '(') {
6714 /* an implicitly declared function */
6715 if (warning.implicit_function_declaration) {
6716 warningf(HERE, "implicit declaration of function '%Y'",
6720 entity = create_implicit_function(symbol, HERE);
6722 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6723 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6729 if (is_declaration(entity)) {
6730 orig_type = entity->declaration.type;
6731 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6732 orig_type = entity->enum_value.enum_type;
6733 } else if (entity->kind == ENTITY_TYPEDEF) {
6734 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6737 return create_invalid_expression();
6739 panic("expected declaration or enum value in reference");
6742 /* we always do the auto-type conversions; the & and sizeof parser contains
6743 * code to revert this! */
6744 type_t *type = automatic_type_conversion(orig_type);
6746 expression_kind_t kind = EXPR_REFERENCE;
6747 if (entity->kind == ENTITY_ENUM_VALUE)
6748 kind = EXPR_REFERENCE_ENUM_VALUE;
6750 expression_t *expression = allocate_expression_zero(kind);
6751 expression->reference.entity = entity;
6752 expression->base.type = type;
6754 /* this declaration is used */
6755 if (is_declaration(entity)) {
6756 entity->declaration.used = true;
6759 if (entity->base.parent_scope != file_scope
6760 && entity->base.parent_scope->depth < current_function->parameters.depth
6761 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6762 if (entity->kind == ENTITY_VARIABLE) {
6763 /* access of a variable from an outer function */
6764 entity->variable.address_taken = true;
6766 current_function->need_closure = true;
6769 /* check for deprecated functions */
6770 if (warning.deprecated_declarations
6771 && is_declaration(entity)
6772 && entity->declaration.modifiers & DM_DEPRECATED) {
6773 declaration_t *declaration = &entity->declaration;
6775 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6776 "function" : "variable";
6778 if (declaration->deprecated_string != NULL) {
6779 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6780 prefix, entity->base.symbol, &entity->base.source_position,
6781 declaration->deprecated_string);
6783 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6784 entity->base.symbol, &entity->base.source_position);
6788 if (warning.init_self && entity == current_init_decl && !in_type_prop
6789 && entity->kind == ENTITY_VARIABLE) {
6790 current_init_decl = NULL;
6791 warningf(HERE, "variable '%#T' is initialized by itself",
6792 entity->declaration.type, entity->base.symbol);
6799 static bool semantic_cast(expression_t *cast)
6801 expression_t *expression = cast->unary.value;
6802 type_t *orig_dest_type = cast->base.type;
6803 type_t *orig_type_right = expression->base.type;
6804 type_t const *dst_type = skip_typeref(orig_dest_type);
6805 type_t const *src_type = skip_typeref(orig_type_right);
6806 source_position_t const *pos = &cast->base.source_position;
6808 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6809 if (dst_type == type_void)
6812 /* only integer and pointer can be casted to pointer */
6813 if (is_type_pointer(dst_type) &&
6814 !is_type_pointer(src_type) &&
6815 !is_type_integer(src_type) &&
6816 is_type_valid(src_type)) {
6817 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6821 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6822 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6826 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6827 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6831 if (warning.cast_qual &&
6832 is_type_pointer(src_type) &&
6833 is_type_pointer(dst_type)) {
6834 type_t *src = skip_typeref(src_type->pointer.points_to);
6835 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6836 unsigned missing_qualifiers =
6837 src->base.qualifiers & ~dst->base.qualifiers;
6838 if (missing_qualifiers != 0) {
6840 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6841 missing_qualifiers, orig_type_right);
6847 static expression_t *parse_compound_literal(type_t *type)
6849 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6851 parse_initializer_env_t env;
6854 env.must_be_constant = false;
6855 initializer_t *initializer = parse_initializer(&env);
6858 expression->compound_literal.initializer = initializer;
6859 expression->compound_literal.type = type;
6860 expression->base.type = automatic_type_conversion(type);
6866 * Parse a cast expression.
6868 static expression_t *parse_cast(void)
6870 add_anchor_token(')');
6872 source_position_t source_position = token.source_position;
6874 type_t *type = parse_typename();
6876 rem_anchor_token(')');
6879 if (token.type == '{') {
6880 return parse_compound_literal(type);
6883 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6884 cast->base.source_position = source_position;
6886 expression_t *value = parse_sub_expression(PREC_CAST);
6887 cast->base.type = type;
6888 cast->unary.value = value;
6890 if (! semantic_cast(cast)) {
6891 /* TODO: record the error in the AST. else it is impossible to detect it */
6896 return create_invalid_expression();
6900 * Parse a statement expression.
6902 static expression_t *parse_statement_expression(void)
6904 add_anchor_token(')');
6906 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6908 statement_t *statement = parse_compound_statement(true);
6909 expression->statement.statement = statement;
6911 /* find last statement and use its type */
6912 type_t *type = type_void;
6913 const statement_t *stmt = statement->compound.statements;
6915 while (stmt->base.next != NULL)
6916 stmt = stmt->base.next;
6918 if (stmt->kind == STATEMENT_EXPRESSION) {
6919 type = stmt->expression.expression->base.type;
6921 } else if (warning.other) {
6922 warningf(&expression->base.source_position, "empty statement expression ({})");
6924 expression->base.type = type;
6926 rem_anchor_token(')');
6934 * Parse a parenthesized expression.
6936 static expression_t *parse_parenthesized_expression(void)
6940 switch (token.type) {
6942 /* gcc extension: a statement expression */
6943 return parse_statement_expression();
6947 return parse_cast();
6949 if (is_typedef_symbol(token.v.symbol)) {
6950 return parse_cast();
6954 add_anchor_token(')');
6955 expression_t *result = parse_expression();
6956 rem_anchor_token(')');
6963 static expression_t *parse_function_keyword(void)
6967 if (current_function == NULL) {
6968 errorf(HERE, "'__func__' used outside of a function");
6971 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6972 expression->base.type = type_char_ptr;
6973 expression->funcname.kind = FUNCNAME_FUNCTION;
6980 static expression_t *parse_pretty_function_keyword(void)
6982 if (current_function == NULL) {
6983 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6986 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6987 expression->base.type = type_char_ptr;
6988 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6990 eat(T___PRETTY_FUNCTION__);
6995 static expression_t *parse_funcsig_keyword(void)
6997 if (current_function == NULL) {
6998 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7001 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7002 expression->base.type = type_char_ptr;
7003 expression->funcname.kind = FUNCNAME_FUNCSIG;
7010 static expression_t *parse_funcdname_keyword(void)
7012 if (current_function == NULL) {
7013 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7016 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7017 expression->base.type = type_char_ptr;
7018 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7020 eat(T___FUNCDNAME__);
7025 static designator_t *parse_designator(void)
7027 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7028 result->source_position = *HERE;
7030 if (token.type != T_IDENTIFIER) {
7031 parse_error_expected("while parsing member designator",
7032 T_IDENTIFIER, NULL);
7035 result->symbol = token.v.symbol;
7038 designator_t *last_designator = result;
7040 if (token.type == '.') {
7042 if (token.type != T_IDENTIFIER) {
7043 parse_error_expected("while parsing member designator",
7044 T_IDENTIFIER, NULL);
7047 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7048 designator->source_position = *HERE;
7049 designator->symbol = token.v.symbol;
7052 last_designator->next = designator;
7053 last_designator = designator;
7056 if (token.type == '[') {
7058 add_anchor_token(']');
7059 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7060 designator->source_position = *HERE;
7061 designator->array_index = parse_expression();
7062 rem_anchor_token(']');
7064 if (designator->array_index == NULL) {
7068 last_designator->next = designator;
7069 last_designator = designator;
7081 * Parse the __builtin_offsetof() expression.
7083 static expression_t *parse_offsetof(void)
7085 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7086 expression->base.type = type_size_t;
7088 eat(T___builtin_offsetof);
7091 add_anchor_token(',');
7092 type_t *type = parse_typename();
7093 rem_anchor_token(',');
7095 add_anchor_token(')');
7096 designator_t *designator = parse_designator();
7097 rem_anchor_token(')');
7100 expression->offsetofe.type = type;
7101 expression->offsetofe.designator = designator;
7104 memset(&path, 0, sizeof(path));
7105 path.top_type = type;
7106 path.path = NEW_ARR_F(type_path_entry_t, 0);
7108 descend_into_subtype(&path);
7110 if (!walk_designator(&path, designator, true)) {
7111 return create_invalid_expression();
7114 DEL_ARR_F(path.path);
7118 return create_invalid_expression();
7122 * Parses a _builtin_va_start() expression.
7124 static expression_t *parse_va_start(void)
7126 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7128 eat(T___builtin_va_start);
7131 add_anchor_token(',');
7132 expression->va_starte.ap = parse_assignment_expression();
7133 rem_anchor_token(',');
7135 expression_t *const expr = parse_assignment_expression();
7136 if (expr->kind == EXPR_REFERENCE) {
7137 entity_t *const entity = expr->reference.entity;
7138 if (entity->base.parent_scope != ¤t_function->parameters
7139 || entity->base.next != NULL
7140 || entity->kind != ENTITY_VARIABLE) {
7141 errorf(&expr->base.source_position,
7142 "second argument of 'va_start' must be last parameter of the current function");
7144 expression->va_starte.parameter = &entity->variable;
7151 return create_invalid_expression();
7155 * Parses a _builtin_va_arg() expression.
7157 static expression_t *parse_va_arg(void)
7159 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7161 eat(T___builtin_va_arg);
7164 expression->va_arge.ap = parse_assignment_expression();
7166 expression->base.type = parse_typename();
7171 return create_invalid_expression();
7174 static expression_t *parse_builtin_symbol(void)
7176 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7178 symbol_t *symbol = token.v.symbol;
7180 expression->builtin_symbol.symbol = symbol;
7183 type_t *type = get_builtin_symbol_type(symbol);
7184 type = automatic_type_conversion(type);
7186 expression->base.type = type;
7191 * Parses a __builtin_constant() expression.
7193 static expression_t *parse_builtin_constant(void)
7195 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7197 eat(T___builtin_constant_p);
7200 add_anchor_token(')');
7201 expression->builtin_constant.value = parse_assignment_expression();
7202 rem_anchor_token(')');
7204 expression->base.type = type_int;
7208 return create_invalid_expression();
7212 * Parses a __builtin_prefetch() expression.
7214 static expression_t *parse_builtin_prefetch(void)
7216 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7218 eat(T___builtin_prefetch);
7221 add_anchor_token(')');
7222 expression->builtin_prefetch.adr = parse_assignment_expression();
7223 if (token.type == ',') {
7225 expression->builtin_prefetch.rw = parse_assignment_expression();
7227 if (token.type == ',') {
7229 expression->builtin_prefetch.locality = parse_assignment_expression();
7231 rem_anchor_token(')');
7233 expression->base.type = type_void;
7237 return create_invalid_expression();
7241 * Parses a __builtin_is_*() compare expression.
7243 static expression_t *parse_compare_builtin(void)
7245 expression_t *expression;
7247 switch (token.type) {
7248 case T___builtin_isgreater:
7249 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7251 case T___builtin_isgreaterequal:
7252 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7254 case T___builtin_isless:
7255 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7257 case T___builtin_islessequal:
7258 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7260 case T___builtin_islessgreater:
7261 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7263 case T___builtin_isunordered:
7264 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7267 internal_errorf(HERE, "invalid compare builtin found");
7269 expression->base.source_position = *HERE;
7273 expression->binary.left = parse_assignment_expression();
7275 expression->binary.right = parse_assignment_expression();
7278 type_t *const orig_type_left = expression->binary.left->base.type;
7279 type_t *const orig_type_right = expression->binary.right->base.type;
7281 type_t *const type_left = skip_typeref(orig_type_left);
7282 type_t *const type_right = skip_typeref(orig_type_right);
7283 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7284 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7285 type_error_incompatible("invalid operands in comparison",
7286 &expression->base.source_position, orig_type_left, orig_type_right);
7289 semantic_comparison(&expression->binary);
7294 return create_invalid_expression();
7299 * Parses a __builtin_expect() expression.
7301 static expression_t *parse_builtin_expect(void)
7303 expression_t *expression
7304 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7306 eat(T___builtin_expect);
7309 expression->binary.left = parse_assignment_expression();
7311 expression->binary.right = parse_constant_expression();
7314 expression->base.type = expression->binary.left->base.type;
7318 return create_invalid_expression();
7323 * Parses a MS assume() expression.
7325 static expression_t *parse_assume(void)
7327 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7332 add_anchor_token(')');
7333 expression->unary.value = parse_assignment_expression();
7334 rem_anchor_token(')');
7337 expression->base.type = type_void;
7340 return create_invalid_expression();
7344 * Return the declaration for a given label symbol or create a new one.
7346 * @param symbol the symbol of the label
7348 static label_t *get_label(symbol_t *symbol)
7351 assert(current_function != NULL);
7353 label = get_entity(symbol, NAMESPACE_LABEL);
7354 /* if we found a local label, we already created the declaration */
7355 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7356 if (label->base.parent_scope != current_scope) {
7357 assert(label->base.parent_scope->depth < current_scope->depth);
7358 current_function->goto_to_outer = true;
7360 return &label->label;
7363 label = get_entity(symbol, NAMESPACE_LABEL);
7364 /* if we found a label in the same function, then we already created the
7367 && label->base.parent_scope == ¤t_function->parameters) {
7368 return &label->label;
7371 /* otherwise we need to create a new one */
7372 label = allocate_entity_zero(ENTITY_LABEL);
7373 label->base.namespc = NAMESPACE_LABEL;
7374 label->base.symbol = symbol;
7378 return &label->label;
7382 * Parses a GNU && label address expression.
7384 static expression_t *parse_label_address(void)
7386 source_position_t source_position = token.source_position;
7388 if (token.type != T_IDENTIFIER) {
7389 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7392 symbol_t *symbol = token.v.symbol;
7395 label_t *label = get_label(symbol);
7397 label->address_taken = true;
7399 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7400 expression->base.source_position = source_position;
7402 /* label address is threaten as a void pointer */
7403 expression->base.type = type_void_ptr;
7404 expression->label_address.label = label;
7407 return create_invalid_expression();
7411 * Parse a microsoft __noop expression.
7413 static expression_t *parse_noop_expression(void)
7415 /* the result is a (int)0 */
7416 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7417 cnst->base.type = type_int;
7418 cnst->conste.v.int_value = 0;
7419 cnst->conste.is_ms_noop = true;
7423 if (token.type == '(') {
7424 /* parse arguments */
7426 add_anchor_token(')');
7427 add_anchor_token(',');
7429 if (token.type != ')') {
7431 (void)parse_assignment_expression();
7432 if (token.type != ',')
7438 rem_anchor_token(',');
7439 rem_anchor_token(')');
7447 * Parses a primary expression.
7449 static expression_t *parse_primary_expression(void)
7451 switch (token.type) {
7452 case T_false: return parse_bool_const(false);
7453 case T_true: return parse_bool_const(true);
7454 case T_INTEGER: return parse_int_const();
7455 case T_CHARACTER_CONSTANT: return parse_character_constant();
7456 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7457 case T_FLOATINGPOINT: return parse_float_const();
7458 case T_STRING_LITERAL:
7459 case T_WIDE_STRING_LITERAL: return parse_string_const();
7460 case T_IDENTIFIER: return parse_reference();
7461 case T___FUNCTION__:
7462 case T___func__: return parse_function_keyword();
7463 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7464 case T___FUNCSIG__: return parse_funcsig_keyword();
7465 case T___FUNCDNAME__: return parse_funcdname_keyword();
7466 case T___builtin_offsetof: return parse_offsetof();
7467 case T___builtin_va_start: return parse_va_start();
7468 case T___builtin_va_arg: return parse_va_arg();
7469 case T___builtin_expect:
7470 case T___builtin_alloca:
7471 case T___builtin_inf:
7472 case T___builtin_inff:
7473 case T___builtin_infl:
7474 case T___builtin_nan:
7475 case T___builtin_nanf:
7476 case T___builtin_nanl:
7477 case T___builtin_huge_val:
7478 case T___builtin_va_end: return parse_builtin_symbol();
7479 case T___builtin_isgreater:
7480 case T___builtin_isgreaterequal:
7481 case T___builtin_isless:
7482 case T___builtin_islessequal:
7483 case T___builtin_islessgreater:
7484 case T___builtin_isunordered: return parse_compare_builtin();
7485 case T___builtin_constant_p: return parse_builtin_constant();
7486 case T___builtin_prefetch: return parse_builtin_prefetch();
7487 case T__assume: return parse_assume();
7490 return parse_label_address();
7493 case '(': return parse_parenthesized_expression();
7494 case T___noop: return parse_noop_expression();
7497 errorf(HERE, "unexpected token %K, expected an expression", &token);
7498 return create_invalid_expression();
7502 * Check if the expression has the character type and issue a warning then.
7504 static void check_for_char_index_type(const expression_t *expression)
7506 type_t *const type = expression->base.type;
7507 const type_t *const base_type = skip_typeref(type);
7509 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7510 warning.char_subscripts) {
7511 warningf(&expression->base.source_position,
7512 "array subscript has type '%T'", type);
7516 static expression_t *parse_array_expression(expression_t *left)
7518 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7521 add_anchor_token(']');
7523 expression_t *inside = parse_expression();
7525 type_t *const orig_type_left = left->base.type;
7526 type_t *const orig_type_inside = inside->base.type;
7528 type_t *const type_left = skip_typeref(orig_type_left);
7529 type_t *const type_inside = skip_typeref(orig_type_inside);
7531 type_t *return_type;
7532 array_access_expression_t *array_access = &expression->array_access;
7533 if (is_type_pointer(type_left)) {
7534 return_type = type_left->pointer.points_to;
7535 array_access->array_ref = left;
7536 array_access->index = inside;
7537 check_for_char_index_type(inside);
7538 } else if (is_type_pointer(type_inside)) {
7539 return_type = type_inside->pointer.points_to;
7540 array_access->array_ref = inside;
7541 array_access->index = left;
7542 array_access->flipped = true;
7543 check_for_char_index_type(left);
7545 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7547 "array access on object with non-pointer types '%T', '%T'",
7548 orig_type_left, orig_type_inside);
7550 return_type = type_error_type;
7551 array_access->array_ref = left;
7552 array_access->index = inside;
7555 expression->base.type = automatic_type_conversion(return_type);
7557 rem_anchor_token(']');
7563 static expression_t *parse_typeprop(expression_kind_t const kind)
7565 expression_t *tp_expression = allocate_expression_zero(kind);
7566 tp_expression->base.type = type_size_t;
7568 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7570 /* we only refer to a type property, mark this case */
7571 bool old = in_type_prop;
7572 in_type_prop = true;
7575 expression_t *expression;
7576 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7578 add_anchor_token(')');
7579 orig_type = parse_typename();
7580 rem_anchor_token(')');
7583 if (token.type == '{') {
7584 /* It was not sizeof(type) after all. It is sizeof of an expression
7585 * starting with a compound literal */
7586 expression = parse_compound_literal(orig_type);
7587 goto typeprop_expression;
7590 expression = parse_sub_expression(PREC_UNARY);
7592 typeprop_expression:
7593 tp_expression->typeprop.tp_expression = expression;
7595 orig_type = revert_automatic_type_conversion(expression);
7596 expression->base.type = orig_type;
7599 tp_expression->typeprop.type = orig_type;
7600 type_t const* const type = skip_typeref(orig_type);
7601 char const* const wrong_type =
7602 is_type_incomplete(type) ? "incomplete" :
7603 type->kind == TYPE_FUNCTION ? "function designator" :
7604 type->kind == TYPE_BITFIELD ? "bitfield" :
7606 if (wrong_type != NULL) {
7607 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7608 errorf(&tp_expression->base.source_position,
7609 "operand of %s expression must not be of %s type '%T'",
7610 what, wrong_type, orig_type);
7615 return tp_expression;
7618 static expression_t *parse_sizeof(void)
7620 return parse_typeprop(EXPR_SIZEOF);
7623 static expression_t *parse_alignof(void)
7625 return parse_typeprop(EXPR_ALIGNOF);
7628 static expression_t *parse_select_expression(expression_t *compound)
7630 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7631 select->select.compound = compound;
7633 assert(token.type == '.' || token.type == T_MINUSGREATER);
7634 bool is_pointer = (token.type == T_MINUSGREATER);
7637 if (token.type != T_IDENTIFIER) {
7638 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7641 symbol_t *symbol = token.v.symbol;
7644 type_t *const orig_type = compound->base.type;
7645 type_t *const type = skip_typeref(orig_type);
7648 bool saw_error = false;
7649 if (is_type_pointer(type)) {
7652 "request for member '%Y' in something not a struct or union, but '%T'",
7656 type_left = skip_typeref(type->pointer.points_to);
7658 if (is_pointer && is_type_valid(type)) {
7659 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7666 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7667 type_left->kind == TYPE_COMPOUND_UNION) {
7668 compound_t *compound = type_left->compound.compound;
7670 if (!compound->complete) {
7671 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7673 goto create_error_entry;
7676 entry = find_compound_entry(compound, symbol);
7677 if (entry == NULL) {
7678 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7679 goto create_error_entry;
7682 if (is_type_valid(type_left) && !saw_error) {
7684 "request for member '%Y' in something not a struct or union, but '%T'",
7688 return create_invalid_expression();
7691 assert(is_declaration(entry));
7692 select->select.compound_entry = entry;
7694 type_t *entry_type = entry->declaration.type;
7696 = get_qualified_type(entry_type, type_left->base.qualifiers);
7698 /* we always do the auto-type conversions; the & and sizeof parser contains
7699 * code to revert this! */
7700 select->base.type = automatic_type_conversion(res_type);
7702 type_t *skipped = skip_typeref(res_type);
7703 if (skipped->kind == TYPE_BITFIELD) {
7704 select->base.type = skipped->bitfield.base_type;
7710 static void check_call_argument(const function_parameter_t *parameter,
7711 call_argument_t *argument, unsigned pos)
7713 type_t *expected_type = parameter->type;
7714 type_t *expected_type_skip = skip_typeref(expected_type);
7715 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7716 expression_t *arg_expr = argument->expression;
7717 type_t *arg_type = skip_typeref(arg_expr->base.type);
7719 /* handle transparent union gnu extension */
7720 if (is_type_union(expected_type_skip)
7721 && (expected_type_skip->base.modifiers
7722 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7723 compound_t *union_decl = expected_type_skip->compound.compound;
7724 type_t *best_type = NULL;
7725 entity_t *entry = union_decl->members.entities;
7726 for ( ; entry != NULL; entry = entry->base.next) {
7727 assert(is_declaration(entry));
7728 type_t *decl_type = entry->declaration.type;
7729 error = semantic_assign(decl_type, arg_expr);
7730 if (error == ASSIGN_ERROR_INCOMPATIBLE
7731 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7734 if (error == ASSIGN_SUCCESS) {
7735 best_type = decl_type;
7736 } else if (best_type == NULL) {
7737 best_type = decl_type;
7741 if (best_type != NULL) {
7742 expected_type = best_type;
7746 error = semantic_assign(expected_type, arg_expr);
7747 argument->expression = create_implicit_cast(argument->expression,
7750 if (error != ASSIGN_SUCCESS) {
7751 /* report exact scope in error messages (like "in argument 3") */
7753 snprintf(buf, sizeof(buf), "call argument %u", pos);
7754 report_assign_error(error, expected_type, arg_expr, buf,
7755 &arg_expr->base.source_position);
7756 } else if (warning.traditional || warning.conversion) {
7757 type_t *const promoted_type = get_default_promoted_type(arg_type);
7758 if (!types_compatible(expected_type_skip, promoted_type) &&
7759 !types_compatible(expected_type_skip, type_void_ptr) &&
7760 !types_compatible(type_void_ptr, promoted_type)) {
7761 /* Deliberately show the skipped types in this warning */
7762 warningf(&arg_expr->base.source_position,
7763 "passing call argument %u as '%T' rather than '%T' due to prototype",
7764 pos, expected_type_skip, promoted_type);
7770 * Parse a call expression, ie. expression '( ... )'.
7772 * @param expression the function address
7774 static expression_t *parse_call_expression(expression_t *expression)
7776 expression_t *result = allocate_expression_zero(EXPR_CALL);
7777 call_expression_t *call = &result->call;
7778 call->function = expression;
7780 type_t *const orig_type = expression->base.type;
7781 type_t *const type = skip_typeref(orig_type);
7783 function_type_t *function_type = NULL;
7784 if (is_type_pointer(type)) {
7785 type_t *const to_type = skip_typeref(type->pointer.points_to);
7787 if (is_type_function(to_type)) {
7788 function_type = &to_type->function;
7789 call->base.type = function_type->return_type;
7793 if (function_type == NULL && is_type_valid(type)) {
7794 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7797 /* parse arguments */
7799 add_anchor_token(')');
7800 add_anchor_token(',');
7802 if (token.type != ')') {
7803 call_argument_t *last_argument = NULL;
7806 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7808 argument->expression = parse_assignment_expression();
7809 if (last_argument == NULL) {
7810 call->arguments = argument;
7812 last_argument->next = argument;
7814 last_argument = argument;
7816 if (token.type != ',')
7821 rem_anchor_token(',');
7822 rem_anchor_token(')');
7825 if (function_type == NULL)
7828 function_parameter_t *parameter = function_type->parameters;
7829 call_argument_t *argument = call->arguments;
7830 if (!function_type->unspecified_parameters) {
7831 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7832 parameter = parameter->next, argument = argument->next) {
7833 check_call_argument(parameter, argument, ++pos);
7836 if (parameter != NULL) {
7837 errorf(HERE, "too few arguments to function '%E'", expression);
7838 } else if (argument != NULL && !function_type->variadic) {
7839 errorf(HERE, "too many arguments to function '%E'", expression);
7843 /* do default promotion */
7844 for (; argument != NULL; argument = argument->next) {
7845 type_t *type = argument->expression->base.type;
7847 type = get_default_promoted_type(type);
7849 argument->expression
7850 = create_implicit_cast(argument->expression, type);
7853 check_format(&result->call);
7855 if (warning.aggregate_return &&
7856 is_type_compound(skip_typeref(function_type->return_type))) {
7857 warningf(&result->base.source_position,
7858 "function call has aggregate value");
7865 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7867 static bool same_compound_type(const type_t *type1, const type_t *type2)
7870 is_type_compound(type1) &&
7871 type1->kind == type2->kind &&
7872 type1->compound.compound == type2->compound.compound;
7875 static expression_t const *get_reference_address(expression_t const *expr)
7877 bool regular_take_address = true;
7879 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7880 expr = expr->unary.value;
7882 regular_take_address = false;
7885 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7888 expr = expr->unary.value;
7891 if (expr->kind != EXPR_REFERENCE)
7894 /* special case for functions which are automatically converted to a
7895 * pointer to function without an extra TAKE_ADDRESS operation */
7896 if (!regular_take_address &&
7897 expr->reference.entity->kind != ENTITY_FUNCTION) {
7904 static void warn_reference_address_as_bool(expression_t const* expr)
7906 if (!warning.address)
7909 expr = get_reference_address(expr);
7911 warningf(&expr->base.source_position,
7912 "the address of '%Y' will always evaluate as 'true'",
7913 expr->reference.entity->base.symbol);
7918 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7920 * @param expression the conditional expression
7922 static expression_t *parse_conditional_expression(expression_t *expression)
7924 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7926 conditional_expression_t *conditional = &result->conditional;
7927 conditional->condition = expression;
7929 warn_reference_address_as_bool(expression);
7932 add_anchor_token(':');
7935 type_t *const condition_type_orig = expression->base.type;
7936 type_t *const condition_type = skip_typeref(condition_type_orig);
7937 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7938 type_error("expected a scalar type in conditional condition",
7939 &expression->base.source_position, condition_type_orig);
7942 expression_t *true_expression = expression;
7943 bool gnu_cond = false;
7944 if (GNU_MODE && token.type == ':') {
7947 true_expression = parse_expression();
7949 rem_anchor_token(':');
7951 expression_t *false_expression =
7952 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7954 type_t *const orig_true_type = true_expression->base.type;
7955 type_t *const orig_false_type = false_expression->base.type;
7956 type_t *const true_type = skip_typeref(orig_true_type);
7957 type_t *const false_type = skip_typeref(orig_false_type);
7960 type_t *result_type;
7961 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7962 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7963 /* ISO/IEC 14882:1998(E) §5.16:2 */
7964 if (true_expression->kind == EXPR_UNARY_THROW) {
7965 result_type = false_type;
7966 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7967 result_type = true_type;
7969 if (warning.other && (
7970 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7971 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7973 warningf(&conditional->base.source_position,
7974 "ISO C forbids conditional expression with only one void side");
7976 result_type = type_void;
7978 } else if (is_type_arithmetic(true_type)
7979 && is_type_arithmetic(false_type)) {
7980 result_type = semantic_arithmetic(true_type, false_type);
7982 true_expression = create_implicit_cast(true_expression, result_type);
7983 false_expression = create_implicit_cast(false_expression, result_type);
7985 conditional->true_expression = true_expression;
7986 conditional->false_expression = false_expression;
7987 conditional->base.type = result_type;
7988 } else if (same_compound_type(true_type, false_type)) {
7989 /* just take 1 of the 2 types */
7990 result_type = true_type;
7991 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7992 type_t *pointer_type;
7994 expression_t *other_expression;
7995 if (is_type_pointer(true_type) &&
7996 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7997 pointer_type = true_type;
7998 other_type = false_type;
7999 other_expression = false_expression;
8001 pointer_type = false_type;
8002 other_type = true_type;
8003 other_expression = true_expression;
8006 if (is_null_pointer_constant(other_expression)) {
8007 result_type = pointer_type;
8008 } else if (is_type_pointer(other_type)) {
8009 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8010 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8013 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8014 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8016 } else if (types_compatible(get_unqualified_type(to1),
8017 get_unqualified_type(to2))) {
8020 if (warning.other) {
8021 warningf(&conditional->base.source_position,
8022 "pointer types '%T' and '%T' in conditional expression are incompatible",
8023 true_type, false_type);
8028 type_t *const type =
8029 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8030 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8031 } else if (is_type_integer(other_type)) {
8032 if (warning.other) {
8033 warningf(&conditional->base.source_position,
8034 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8036 result_type = pointer_type;
8038 if (is_type_valid(other_type)) {
8039 type_error_incompatible("while parsing conditional",
8040 &expression->base.source_position, true_type, false_type);
8042 result_type = type_error_type;
8045 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8046 type_error_incompatible("while parsing conditional",
8047 &conditional->base.source_position, true_type,
8050 result_type = type_error_type;
8053 conditional->true_expression
8054 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8055 conditional->false_expression
8056 = create_implicit_cast(false_expression, result_type);
8057 conditional->base.type = result_type;
8060 return create_invalid_expression();
8064 * Parse an extension expression.
8066 static expression_t *parse_extension(void)
8068 eat(T___extension__);
8070 bool old_gcc_extension = in_gcc_extension;
8071 in_gcc_extension = true;
8072 expression_t *expression = parse_sub_expression(PREC_UNARY);
8073 in_gcc_extension = old_gcc_extension;
8078 * Parse a __builtin_classify_type() expression.
8080 static expression_t *parse_builtin_classify_type(void)
8082 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8083 result->base.type = type_int;
8085 eat(T___builtin_classify_type);
8088 add_anchor_token(')');
8089 expression_t *expression = parse_expression();
8090 rem_anchor_token(')');
8092 result->classify_type.type_expression = expression;
8096 return create_invalid_expression();
8100 * Parse a delete expression
8101 * ISO/IEC 14882:1998(E) §5.3.5
8103 static expression_t *parse_delete(void)
8105 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8106 result->base.type = type_void;
8110 if (token.type == '[') {
8112 result->kind = EXPR_UNARY_DELETE_ARRAY;
8117 expression_t *const value = parse_sub_expression(PREC_CAST);
8118 result->unary.value = value;
8120 type_t *const type = skip_typeref(value->base.type);
8121 if (!is_type_pointer(type)) {
8122 errorf(&value->base.source_position,
8123 "operand of delete must have pointer type");
8124 } else if (warning.other &&
8125 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8126 warningf(&value->base.source_position,
8127 "deleting 'void*' is undefined");
8134 * Parse a throw expression
8135 * ISO/IEC 14882:1998(E) §15:1
8137 static expression_t *parse_throw(void)
8139 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8140 result->base.type = type_void;
8144 expression_t *value = NULL;
8145 switch (token.type) {
8147 value = parse_assignment_expression();
8148 /* ISO/IEC 14882:1998(E) §15.1:3 */
8149 type_t *const orig_type = value->base.type;
8150 type_t *const type = skip_typeref(orig_type);
8151 if (is_type_incomplete(type)) {
8152 errorf(&value->base.source_position,
8153 "cannot throw object of incomplete type '%T'", orig_type);
8154 } else if (is_type_pointer(type)) {
8155 type_t *const points_to = skip_typeref(type->pointer.points_to);
8156 if (is_type_incomplete(points_to) &&
8157 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8158 errorf(&value->base.source_position,
8159 "cannot throw pointer to incomplete type '%T'", orig_type);
8167 result->unary.value = value;
8172 static bool check_pointer_arithmetic(const source_position_t *source_position,
8173 type_t *pointer_type,
8174 type_t *orig_pointer_type)
8176 type_t *points_to = pointer_type->pointer.points_to;
8177 points_to = skip_typeref(points_to);
8179 if (is_type_incomplete(points_to)) {
8180 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8181 errorf(source_position,
8182 "arithmetic with pointer to incomplete type '%T' not allowed",
8185 } else if (warning.pointer_arith) {
8186 warningf(source_position,
8187 "pointer of type '%T' used in arithmetic",
8190 } else if (is_type_function(points_to)) {
8192 errorf(source_position,
8193 "arithmetic with pointer to function type '%T' not allowed",
8196 } else if (warning.pointer_arith) {
8197 warningf(source_position,
8198 "pointer to a function '%T' used in arithmetic",
8205 static bool is_lvalue(const expression_t *expression)
8207 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8208 switch (expression->kind) {
8209 case EXPR_REFERENCE:
8210 case EXPR_ARRAY_ACCESS:
8212 case EXPR_UNARY_DEREFERENCE:
8216 /* Claim it is an lvalue, if the type is invalid. There was a parse
8217 * error before, which maybe prevented properly recognizing it as
8219 return !is_type_valid(skip_typeref(expression->base.type));
8223 static void semantic_incdec(unary_expression_t *expression)
8225 type_t *const orig_type = expression->value->base.type;
8226 type_t *const type = skip_typeref(orig_type);
8227 if (is_type_pointer(type)) {
8228 if (!check_pointer_arithmetic(&expression->base.source_position,
8232 } else if (!is_type_real(type) && is_type_valid(type)) {
8233 /* TODO: improve error message */
8234 errorf(&expression->base.source_position,
8235 "operation needs an arithmetic or pointer type");
8238 if (!is_lvalue(expression->value)) {
8239 /* TODO: improve error message */
8240 errorf(&expression->base.source_position, "lvalue required as operand");
8242 expression->base.type = orig_type;
8245 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8247 type_t *const orig_type = expression->value->base.type;
8248 type_t *const type = skip_typeref(orig_type);
8249 if (!is_type_arithmetic(type)) {
8250 if (is_type_valid(type)) {
8251 /* TODO: improve error message */
8252 errorf(&expression->base.source_position,
8253 "operation needs an arithmetic type");
8258 expression->base.type = orig_type;
8261 static void semantic_unexpr_plus(unary_expression_t *expression)
8263 semantic_unexpr_arithmetic(expression);
8264 if (warning.traditional)
8265 warningf(&expression->base.source_position,
8266 "traditional C rejects the unary plus operator");
8269 static void semantic_not(unary_expression_t *expression)
8271 type_t *const orig_type = expression->value->base.type;
8272 type_t *const type = skip_typeref(orig_type);
8273 if (!is_type_scalar(type) && is_type_valid(type)) {
8274 errorf(&expression->base.source_position,
8275 "operand of ! must be of scalar type");
8278 warn_reference_address_as_bool(expression->value);
8280 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8283 static void semantic_unexpr_integer(unary_expression_t *expression)
8285 type_t *const orig_type = expression->value->base.type;
8286 type_t *const type = skip_typeref(orig_type);
8287 if (!is_type_integer(type)) {
8288 if (is_type_valid(type)) {
8289 errorf(&expression->base.source_position,
8290 "operand of ~ must be of integer type");
8295 expression->base.type = orig_type;
8298 static void semantic_dereference(unary_expression_t *expression)
8300 type_t *const orig_type = expression->value->base.type;
8301 type_t *const type = skip_typeref(orig_type);
8302 if (!is_type_pointer(type)) {
8303 if (is_type_valid(type)) {
8304 errorf(&expression->base.source_position,
8305 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8310 type_t *result_type = type->pointer.points_to;
8311 result_type = automatic_type_conversion(result_type);
8312 expression->base.type = result_type;
8316 * Record that an address is taken (expression represents an lvalue).
8318 * @param expression the expression
8319 * @param may_be_register if true, the expression might be an register
8321 static void set_address_taken(expression_t *expression, bool may_be_register)
8323 if (expression->kind != EXPR_REFERENCE)
8326 entity_t *const entity = expression->reference.entity;
8328 if (entity->kind != ENTITY_VARIABLE)
8331 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8332 && !may_be_register) {
8333 errorf(&expression->base.source_position,
8334 "address of register variable '%Y' requested",
8335 entity->base.symbol);
8338 entity->variable.address_taken = true;
8342 * Check the semantic of the address taken expression.
8344 static void semantic_take_addr(unary_expression_t *expression)
8346 expression_t *value = expression->value;
8347 value->base.type = revert_automatic_type_conversion(value);
8349 type_t *orig_type = value->base.type;
8350 type_t *type = skip_typeref(orig_type);
8351 if (!is_type_valid(type))
8355 if (!is_lvalue(value)) {
8356 errorf(&expression->base.source_position, "'&' requires an lvalue");
8358 if (type->kind == TYPE_BITFIELD) {
8359 errorf(&expression->base.source_position,
8360 "'&' not allowed on object with bitfield type '%T'",
8364 set_address_taken(value, false);
8366 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8369 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8370 static expression_t *parse_##unexpression_type(void) \
8372 expression_t *unary_expression \
8373 = allocate_expression_zero(unexpression_type); \
8375 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8377 sfunc(&unary_expression->unary); \
8379 return unary_expression; \
8382 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8383 semantic_unexpr_arithmetic)
8384 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8385 semantic_unexpr_plus)
8386 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8388 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8389 semantic_dereference)
8390 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8392 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8393 semantic_unexpr_integer)
8394 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8396 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8399 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8401 static expression_t *parse_##unexpression_type(expression_t *left) \
8403 expression_t *unary_expression \
8404 = allocate_expression_zero(unexpression_type); \
8406 unary_expression->unary.value = left; \
8408 sfunc(&unary_expression->unary); \
8410 return unary_expression; \
8413 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8414 EXPR_UNARY_POSTFIX_INCREMENT,
8416 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8417 EXPR_UNARY_POSTFIX_DECREMENT,
8420 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8422 /* TODO: handle complex + imaginary types */
8424 type_left = get_unqualified_type(type_left);
8425 type_right = get_unqualified_type(type_right);
8427 /* § 6.3.1.8 Usual arithmetic conversions */
8428 if (type_left == type_long_double || type_right == type_long_double) {
8429 return type_long_double;
8430 } else if (type_left == type_double || type_right == type_double) {
8432 } else if (type_left == type_float || type_right == type_float) {
8436 type_left = promote_integer(type_left);
8437 type_right = promote_integer(type_right);
8439 if (type_left == type_right)
8442 bool const signed_left = is_type_signed(type_left);
8443 bool const signed_right = is_type_signed(type_right);
8444 int const rank_left = get_rank(type_left);
8445 int const rank_right = get_rank(type_right);
8447 if (signed_left == signed_right)
8448 return rank_left >= rank_right ? type_left : type_right;
8457 u_rank = rank_right;
8458 u_type = type_right;
8460 s_rank = rank_right;
8461 s_type = type_right;
8466 if (u_rank >= s_rank)
8469 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8471 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8472 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8476 case ATOMIC_TYPE_INT: return type_unsigned_int;
8477 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8478 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8480 default: panic("invalid atomic type");
8485 * Check the semantic restrictions for a binary expression.
8487 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8489 expression_t *const left = expression->left;
8490 expression_t *const right = expression->right;
8491 type_t *const orig_type_left = left->base.type;
8492 type_t *const orig_type_right = right->base.type;
8493 type_t *const type_left = skip_typeref(orig_type_left);
8494 type_t *const type_right = skip_typeref(orig_type_right);
8496 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8497 /* TODO: improve error message */
8498 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8499 errorf(&expression->base.source_position,
8500 "operation needs arithmetic types");
8505 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8506 expression->left = create_implicit_cast(left, arithmetic_type);
8507 expression->right = create_implicit_cast(right, arithmetic_type);
8508 expression->base.type = arithmetic_type;
8511 static void warn_div_by_zero(binary_expression_t const *const expression)
8513 if (!warning.div_by_zero ||
8514 !is_type_integer(expression->base.type))
8517 expression_t const *const right = expression->right;
8518 /* The type of the right operand can be different for /= */
8519 if (is_type_integer(right->base.type) &&
8520 is_constant_expression(right) &&
8521 fold_constant(right) == 0) {
8522 warningf(&expression->base.source_position, "division by zero");
8527 * Check the semantic restrictions for a div/mod expression.
8529 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8530 semantic_binexpr_arithmetic(expression);
8531 warn_div_by_zero(expression);
8534 static void semantic_shift_op(binary_expression_t *expression)
8536 expression_t *const left = expression->left;
8537 expression_t *const right = expression->right;
8538 type_t *const orig_type_left = left->base.type;
8539 type_t *const orig_type_right = right->base.type;
8540 type_t * type_left = skip_typeref(orig_type_left);
8541 type_t * type_right = skip_typeref(orig_type_right);
8543 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8544 /* TODO: improve error message */
8545 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8546 errorf(&expression->base.source_position,
8547 "operands of shift operation must have integer types");
8552 type_left = promote_integer(type_left);
8553 type_right = promote_integer(type_right);
8555 expression->left = create_implicit_cast(left, type_left);
8556 expression->right = create_implicit_cast(right, type_right);
8557 expression->base.type = type_left;
8560 static void semantic_add(binary_expression_t *expression)
8562 expression_t *const left = expression->left;
8563 expression_t *const right = expression->right;
8564 type_t *const orig_type_left = left->base.type;
8565 type_t *const orig_type_right = right->base.type;
8566 type_t *const type_left = skip_typeref(orig_type_left);
8567 type_t *const type_right = skip_typeref(orig_type_right);
8570 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8571 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8572 expression->left = create_implicit_cast(left, arithmetic_type);
8573 expression->right = create_implicit_cast(right, arithmetic_type);
8574 expression->base.type = arithmetic_type;
8576 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8577 check_pointer_arithmetic(&expression->base.source_position,
8578 type_left, orig_type_left);
8579 expression->base.type = type_left;
8580 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8581 check_pointer_arithmetic(&expression->base.source_position,
8582 type_right, orig_type_right);
8583 expression->base.type = type_right;
8584 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8585 errorf(&expression->base.source_position,
8586 "invalid operands to binary + ('%T', '%T')",
8587 orig_type_left, orig_type_right);
8591 static void semantic_sub(binary_expression_t *expression)
8593 expression_t *const left = expression->left;
8594 expression_t *const right = expression->right;
8595 type_t *const orig_type_left = left->base.type;
8596 type_t *const orig_type_right = right->base.type;
8597 type_t *const type_left = skip_typeref(orig_type_left);
8598 type_t *const type_right = skip_typeref(orig_type_right);
8599 source_position_t const *const pos = &expression->base.source_position;
8602 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8603 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8604 expression->left = create_implicit_cast(left, arithmetic_type);
8605 expression->right = create_implicit_cast(right, arithmetic_type);
8606 expression->base.type = arithmetic_type;
8608 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8609 check_pointer_arithmetic(&expression->base.source_position,
8610 type_left, orig_type_left);
8611 expression->base.type = type_left;
8612 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8613 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8614 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8615 if (!types_compatible(unqual_left, unqual_right)) {
8617 "subtracting pointers to incompatible types '%T' and '%T'",
8618 orig_type_left, orig_type_right);
8619 } else if (!is_type_object(unqual_left)) {
8620 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8621 errorf(pos, "subtracting pointers to non-object types '%T'",
8623 } else if (warning.other) {
8624 warningf(pos, "subtracting pointers to void");
8627 expression->base.type = type_ptrdiff_t;
8628 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8629 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8630 orig_type_left, orig_type_right);
8634 static void warn_string_literal_address(expression_t const* expr)
8636 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8637 expr = expr->unary.value;
8638 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8640 expr = expr->unary.value;
8643 if (expr->kind == EXPR_STRING_LITERAL ||
8644 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8645 warningf(&expr->base.source_position,
8646 "comparison with string literal results in unspecified behaviour");
8651 * Check the semantics of comparison expressions.
8653 * @param expression The expression to check.
8655 static void semantic_comparison(binary_expression_t *expression)
8657 expression_t *left = expression->left;
8658 expression_t *right = expression->right;
8660 if (warning.address) {
8661 warn_string_literal_address(left);
8662 warn_string_literal_address(right);
8664 expression_t const* const func_left = get_reference_address(left);
8665 if (func_left != NULL && is_null_pointer_constant(right)) {
8666 warningf(&expression->base.source_position,
8667 "the address of '%Y' will never be NULL",
8668 func_left->reference.entity->base.symbol);
8671 expression_t const* const func_right = get_reference_address(right);
8672 if (func_right != NULL && is_null_pointer_constant(right)) {
8673 warningf(&expression->base.source_position,
8674 "the address of '%Y' will never be NULL",
8675 func_right->reference.entity->base.symbol);
8679 type_t *orig_type_left = left->base.type;
8680 type_t *orig_type_right = right->base.type;
8681 type_t *type_left = skip_typeref(orig_type_left);
8682 type_t *type_right = skip_typeref(orig_type_right);
8684 /* TODO non-arithmetic types */
8685 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8686 /* test for signed vs unsigned compares */
8687 if (warning.sign_compare &&
8688 (expression->base.kind != EXPR_BINARY_EQUAL &&
8689 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8690 (is_type_signed(type_left) != is_type_signed(type_right))) {
8692 /* check if 1 of the operands is a constant, in this case we just
8693 * check wether we can safely represent the resulting constant in
8694 * the type of the other operand. */
8695 expression_t *const_expr = NULL;
8696 expression_t *other_expr = NULL;
8698 if (is_constant_expression(left)) {
8701 } else if (is_constant_expression(right)) {
8706 if (const_expr != NULL) {
8707 type_t *other_type = skip_typeref(other_expr->base.type);
8708 long val = fold_constant(const_expr);
8709 /* TODO: check if val can be represented by other_type */
8713 warningf(&expression->base.source_position,
8714 "comparison between signed and unsigned");
8716 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8717 expression->left = create_implicit_cast(left, arithmetic_type);
8718 expression->right = create_implicit_cast(right, arithmetic_type);
8719 expression->base.type = arithmetic_type;
8720 if (warning.float_equal &&
8721 (expression->base.kind == EXPR_BINARY_EQUAL ||
8722 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8723 is_type_float(arithmetic_type)) {
8724 warningf(&expression->base.source_position,
8725 "comparing floating point with == or != is unsafe");
8727 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8728 /* TODO check compatibility */
8729 } else if (is_type_pointer(type_left)) {
8730 expression->right = create_implicit_cast(right, type_left);
8731 } else if (is_type_pointer(type_right)) {
8732 expression->left = create_implicit_cast(left, type_right);
8733 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8734 type_error_incompatible("invalid operands in comparison",
8735 &expression->base.source_position,
8736 type_left, type_right);
8738 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8742 * Checks if a compound type has constant fields.
8744 static bool has_const_fields(const compound_type_t *type)
8746 compound_t *compound = type->compound;
8747 entity_t *entry = compound->members.entities;
8749 for (; entry != NULL; entry = entry->base.next) {
8750 if (!is_declaration(entry))
8753 const type_t *decl_type = skip_typeref(entry->declaration.type);
8754 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8761 static bool is_valid_assignment_lhs(expression_t const* const left)
8763 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8764 type_t *const type_left = skip_typeref(orig_type_left);
8766 if (!is_lvalue(left)) {
8767 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8772 if (is_type_array(type_left)) {
8773 errorf(HERE, "cannot assign to arrays ('%E')", left);
8776 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8777 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8781 if (is_type_incomplete(type_left)) {
8782 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8783 left, orig_type_left);
8786 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8787 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8788 left, orig_type_left);
8795 static void semantic_arithmetic_assign(binary_expression_t *expression)
8797 expression_t *left = expression->left;
8798 expression_t *right = expression->right;
8799 type_t *orig_type_left = left->base.type;
8800 type_t *orig_type_right = right->base.type;
8802 if (!is_valid_assignment_lhs(left))
8805 type_t *type_left = skip_typeref(orig_type_left);
8806 type_t *type_right = skip_typeref(orig_type_right);
8808 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8809 /* TODO: improve error message */
8810 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8811 errorf(&expression->base.source_position,
8812 "operation needs arithmetic types");
8817 /* combined instructions are tricky. We can't create an implicit cast on
8818 * the left side, because we need the uncasted form for the store.
8819 * The ast2firm pass has to know that left_type must be right_type
8820 * for the arithmetic operation and create a cast by itself */
8821 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8822 expression->right = create_implicit_cast(right, arithmetic_type);
8823 expression->base.type = type_left;
8826 static void semantic_divmod_assign(binary_expression_t *expression)
8828 semantic_arithmetic_assign(expression);
8829 warn_div_by_zero(expression);
8832 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8834 expression_t *const left = expression->left;
8835 expression_t *const right = expression->right;
8836 type_t *const orig_type_left = left->base.type;
8837 type_t *const orig_type_right = right->base.type;
8838 type_t *const type_left = skip_typeref(orig_type_left);
8839 type_t *const type_right = skip_typeref(orig_type_right);
8841 if (!is_valid_assignment_lhs(left))
8844 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8845 /* combined instructions are tricky. We can't create an implicit cast on
8846 * the left side, because we need the uncasted form for the store.
8847 * The ast2firm pass has to know that left_type must be right_type
8848 * for the arithmetic operation and create a cast by itself */
8849 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8850 expression->right = create_implicit_cast(right, arithmetic_type);
8851 expression->base.type = type_left;
8852 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8853 check_pointer_arithmetic(&expression->base.source_position,
8854 type_left, orig_type_left);
8855 expression->base.type = type_left;
8856 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8857 errorf(&expression->base.source_position,
8858 "incompatible types '%T' and '%T' in assignment",
8859 orig_type_left, orig_type_right);
8864 * Check the semantic restrictions of a logical expression.
8866 static void semantic_logical_op(binary_expression_t *expression)
8868 expression_t *const left = expression->left;
8869 expression_t *const right = expression->right;
8870 type_t *const orig_type_left = left->base.type;
8871 type_t *const orig_type_right = right->base.type;
8872 type_t *const type_left = skip_typeref(orig_type_left);
8873 type_t *const type_right = skip_typeref(orig_type_right);
8875 warn_reference_address_as_bool(left);
8876 warn_reference_address_as_bool(right);
8878 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8879 /* TODO: improve error message */
8880 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8881 errorf(&expression->base.source_position,
8882 "operation needs scalar types");
8887 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8891 * Check the semantic restrictions of a binary assign expression.
8893 static void semantic_binexpr_assign(binary_expression_t *expression)
8895 expression_t *left = expression->left;
8896 type_t *orig_type_left = left->base.type;
8898 if (!is_valid_assignment_lhs(left))
8901 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8902 report_assign_error(error, orig_type_left, expression->right,
8903 "assignment", &left->base.source_position);
8904 expression->right = create_implicit_cast(expression->right, orig_type_left);
8905 expression->base.type = orig_type_left;
8909 * Determine if the outermost operation (or parts thereof) of the given
8910 * expression has no effect in order to generate a warning about this fact.
8911 * Therefore in some cases this only examines some of the operands of the
8912 * expression (see comments in the function and examples below).
8914 * f() + 23; // warning, because + has no effect
8915 * x || f(); // no warning, because x controls execution of f()
8916 * x ? y : f(); // warning, because y has no effect
8917 * (void)x; // no warning to be able to suppress the warning
8918 * This function can NOT be used for an "expression has definitely no effect"-
8920 static bool expression_has_effect(const expression_t *const expr)
8922 switch (expr->kind) {
8923 case EXPR_UNKNOWN: break;
8924 case EXPR_INVALID: return true; /* do NOT warn */
8925 case EXPR_REFERENCE: return false;
8926 case EXPR_REFERENCE_ENUM_VALUE: return false;
8927 /* suppress the warning for microsoft __noop operations */
8928 case EXPR_CONST: return expr->conste.is_ms_noop;
8929 case EXPR_CHARACTER_CONSTANT: return false;
8930 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8931 case EXPR_STRING_LITERAL: return false;
8932 case EXPR_WIDE_STRING_LITERAL: return false;
8933 case EXPR_LABEL_ADDRESS: return false;
8936 const call_expression_t *const call = &expr->call;
8937 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8940 switch (call->function->builtin_symbol.symbol->ID) {
8941 case T___builtin_va_end: return true;
8942 default: return false;
8946 /* Generate the warning if either the left or right hand side of a
8947 * conditional expression has no effect */
8948 case EXPR_CONDITIONAL: {
8949 const conditional_expression_t *const cond = &expr->conditional;
8951 expression_has_effect(cond->true_expression) &&
8952 expression_has_effect(cond->false_expression);
8955 case EXPR_SELECT: return false;
8956 case EXPR_ARRAY_ACCESS: return false;
8957 case EXPR_SIZEOF: return false;
8958 case EXPR_CLASSIFY_TYPE: return false;
8959 case EXPR_ALIGNOF: return false;
8961 case EXPR_FUNCNAME: return false;
8962 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8963 case EXPR_BUILTIN_CONSTANT_P: return false;
8964 case EXPR_BUILTIN_PREFETCH: return true;
8965 case EXPR_OFFSETOF: return false;
8966 case EXPR_VA_START: return true;
8967 case EXPR_VA_ARG: return true;
8968 case EXPR_STATEMENT: return true; // TODO
8969 case EXPR_COMPOUND_LITERAL: return false;
8971 case EXPR_UNARY_NEGATE: return false;
8972 case EXPR_UNARY_PLUS: return false;
8973 case EXPR_UNARY_BITWISE_NEGATE: return false;
8974 case EXPR_UNARY_NOT: return false;
8975 case EXPR_UNARY_DEREFERENCE: return false;
8976 case EXPR_UNARY_TAKE_ADDRESS: return false;
8977 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8978 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8979 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8980 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8982 /* Treat void casts as if they have an effect in order to being able to
8983 * suppress the warning */
8984 case EXPR_UNARY_CAST: {
8985 type_t *const type = skip_typeref(expr->base.type);
8986 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8989 case EXPR_UNARY_CAST_IMPLICIT: return true;
8990 case EXPR_UNARY_ASSUME: return true;
8991 case EXPR_UNARY_DELETE: return true;
8992 case EXPR_UNARY_DELETE_ARRAY: return true;
8993 case EXPR_UNARY_THROW: return true;
8995 case EXPR_BINARY_ADD: return false;
8996 case EXPR_BINARY_SUB: return false;
8997 case EXPR_BINARY_MUL: return false;
8998 case EXPR_BINARY_DIV: return false;
8999 case EXPR_BINARY_MOD: return false;
9000 case EXPR_BINARY_EQUAL: return false;
9001 case EXPR_BINARY_NOTEQUAL: return false;
9002 case EXPR_BINARY_LESS: return false;
9003 case EXPR_BINARY_LESSEQUAL: return false;
9004 case EXPR_BINARY_GREATER: return false;
9005 case EXPR_BINARY_GREATEREQUAL: return false;
9006 case EXPR_BINARY_BITWISE_AND: return false;
9007 case EXPR_BINARY_BITWISE_OR: return false;
9008 case EXPR_BINARY_BITWISE_XOR: return false;
9009 case EXPR_BINARY_SHIFTLEFT: return false;
9010 case EXPR_BINARY_SHIFTRIGHT: return false;
9011 case EXPR_BINARY_ASSIGN: return true;
9012 case EXPR_BINARY_MUL_ASSIGN: return true;
9013 case EXPR_BINARY_DIV_ASSIGN: return true;
9014 case EXPR_BINARY_MOD_ASSIGN: return true;
9015 case EXPR_BINARY_ADD_ASSIGN: return true;
9016 case EXPR_BINARY_SUB_ASSIGN: return true;
9017 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9018 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9019 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9020 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9021 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9023 /* Only examine the right hand side of && and ||, because the left hand
9024 * side already has the effect of controlling the execution of the right
9026 case EXPR_BINARY_LOGICAL_AND:
9027 case EXPR_BINARY_LOGICAL_OR:
9028 /* Only examine the right hand side of a comma expression, because the left
9029 * hand side has a separate warning */
9030 case EXPR_BINARY_COMMA:
9031 return expression_has_effect(expr->binary.right);
9033 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9034 case EXPR_BINARY_ISGREATER: return false;
9035 case EXPR_BINARY_ISGREATEREQUAL: return false;
9036 case EXPR_BINARY_ISLESS: return false;
9037 case EXPR_BINARY_ISLESSEQUAL: return false;
9038 case EXPR_BINARY_ISLESSGREATER: return false;
9039 case EXPR_BINARY_ISUNORDERED: return false;
9042 internal_errorf(HERE, "unexpected expression");
9045 static void semantic_comma(binary_expression_t *expression)
9047 if (warning.unused_value) {
9048 const expression_t *const left = expression->left;
9049 if (!expression_has_effect(left)) {
9050 warningf(&left->base.source_position,
9051 "left-hand operand of comma expression has no effect");
9054 expression->base.type = expression->right->base.type;
9058 * @param prec_r precedence of the right operand
9060 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9061 static expression_t *parse_##binexpression_type(expression_t *left) \
9063 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9064 binexpr->binary.left = left; \
9067 expression_t *right = parse_sub_expression(prec_r); \
9069 binexpr->binary.right = right; \
9070 sfunc(&binexpr->binary); \
9075 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9076 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9077 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9078 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9079 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9080 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9081 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9082 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9083 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9084 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9085 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9086 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9087 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9088 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9089 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9090 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9091 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9092 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9093 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9094 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9095 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9096 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9097 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9098 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9099 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9100 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9101 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9102 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9103 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9104 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9107 static expression_t *parse_sub_expression(precedence_t precedence)
9109 if (token.type < 0) {
9110 return expected_expression_error();
9113 expression_parser_function_t *parser
9114 = &expression_parsers[token.type];
9115 source_position_t source_position = token.source_position;
9118 if (parser->parser != NULL) {
9119 left = parser->parser();
9121 left = parse_primary_expression();
9123 assert(left != NULL);
9124 left->base.source_position = source_position;
9127 if (token.type < 0) {
9128 return expected_expression_error();
9131 parser = &expression_parsers[token.type];
9132 if (parser->infix_parser == NULL)
9134 if (parser->infix_precedence < precedence)
9137 left = parser->infix_parser(left);
9139 assert(left != NULL);
9140 assert(left->kind != EXPR_UNKNOWN);
9141 left->base.source_position = source_position;
9148 * Parse an expression.
9150 static expression_t *parse_expression(void)
9152 return parse_sub_expression(PREC_EXPRESSION);
9156 * Register a parser for a prefix-like operator.
9158 * @param parser the parser function
9159 * @param token_type the token type of the prefix token
9161 static void register_expression_parser(parse_expression_function parser,
9164 expression_parser_function_t *entry = &expression_parsers[token_type];
9166 if (entry->parser != NULL) {
9167 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9168 panic("trying to register multiple expression parsers for a token");
9170 entry->parser = parser;
9174 * Register a parser for an infix operator with given precedence.
9176 * @param parser the parser function
9177 * @param token_type the token type of the infix operator
9178 * @param precedence the precedence of the operator
9180 static void register_infix_parser(parse_expression_infix_function parser,
9181 int token_type, unsigned precedence)
9183 expression_parser_function_t *entry = &expression_parsers[token_type];
9185 if (entry->infix_parser != NULL) {
9186 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9187 panic("trying to register multiple infix expression parsers for a "
9190 entry->infix_parser = parser;
9191 entry->infix_precedence = precedence;
9195 * Initialize the expression parsers.
9197 static void init_expression_parsers(void)
9199 memset(&expression_parsers, 0, sizeof(expression_parsers));
9201 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9202 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9203 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9204 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9205 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9206 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9207 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9208 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9209 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9210 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9211 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9212 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9213 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9214 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9215 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9216 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9217 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9218 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9219 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9220 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9221 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9222 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9223 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9224 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9225 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9226 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9227 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9228 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9229 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9230 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9231 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9232 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9233 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9234 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9235 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9236 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9237 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9239 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9240 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9241 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9242 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9243 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9244 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9245 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9246 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9247 register_expression_parser(parse_sizeof, T_sizeof);
9248 register_expression_parser(parse_alignof, T___alignof__);
9249 register_expression_parser(parse_extension, T___extension__);
9250 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9251 register_expression_parser(parse_delete, T_delete);
9252 register_expression_parser(parse_throw, T_throw);
9256 * Parse a asm statement arguments specification.
9258 static asm_argument_t *parse_asm_arguments(bool is_out)
9260 asm_argument_t *result = NULL;
9261 asm_argument_t **anchor = &result;
9263 while (token.type == T_STRING_LITERAL || token.type == '[') {
9264 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9265 memset(argument, 0, sizeof(argument[0]));
9267 if (token.type == '[') {
9269 if (token.type != T_IDENTIFIER) {
9270 parse_error_expected("while parsing asm argument",
9271 T_IDENTIFIER, NULL);
9274 argument->symbol = token.v.symbol;
9279 argument->constraints = parse_string_literals();
9281 add_anchor_token(')');
9282 expression_t *expression = parse_expression();
9283 rem_anchor_token(')');
9285 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9286 * change size or type representation (e.g. int -> long is ok, but
9287 * int -> float is not) */
9288 if (expression->kind == EXPR_UNARY_CAST) {
9289 type_t *const type = expression->base.type;
9290 type_kind_t const kind = type->kind;
9291 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9294 if (kind == TYPE_ATOMIC) {
9295 atomic_type_kind_t const akind = type->atomic.akind;
9296 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9297 size = get_atomic_type_size(akind);
9299 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9300 size = get_atomic_type_size(get_intptr_kind());
9304 expression_t *const value = expression->unary.value;
9305 type_t *const value_type = value->base.type;
9306 type_kind_t const value_kind = value_type->kind;
9308 unsigned value_flags;
9309 unsigned value_size;
9310 if (value_kind == TYPE_ATOMIC) {
9311 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9312 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9313 value_size = get_atomic_type_size(value_akind);
9314 } else if (value_kind == TYPE_POINTER) {
9315 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9316 value_size = get_atomic_type_size(get_intptr_kind());
9321 if (value_flags != flags || value_size != size)
9325 } while (expression->kind == EXPR_UNARY_CAST);
9329 if (!is_lvalue(expression)) {
9330 errorf(&expression->base.source_position,
9331 "asm output argument is not an lvalue");
9334 if (argument->constraints.begin[0] == '+')
9335 mark_vars_read(expression, NULL);
9337 mark_vars_read(expression, NULL);
9339 argument->expression = expression;
9342 set_address_taken(expression, true);
9345 anchor = &argument->next;
9347 if (token.type != ',')
9358 * Parse a asm statement clobber specification.
9360 static asm_clobber_t *parse_asm_clobbers(void)
9362 asm_clobber_t *result = NULL;
9363 asm_clobber_t *last = NULL;
9365 while (token.type == T_STRING_LITERAL) {
9366 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9367 clobber->clobber = parse_string_literals();
9370 last->next = clobber;
9376 if (token.type != ',')
9385 * Parse an asm statement.
9387 static statement_t *parse_asm_statement(void)
9389 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9390 asm_statement_t *asm_statement = &statement->asms;
9394 if (token.type == T_volatile) {
9396 asm_statement->is_volatile = true;
9400 add_anchor_token(')');
9401 add_anchor_token(':');
9402 asm_statement->asm_text = parse_string_literals();
9404 if (token.type != ':') {
9405 rem_anchor_token(':');
9410 asm_statement->outputs = parse_asm_arguments(true);
9411 if (token.type != ':') {
9412 rem_anchor_token(':');
9417 asm_statement->inputs = parse_asm_arguments(false);
9418 if (token.type != ':') {
9419 rem_anchor_token(':');
9422 rem_anchor_token(':');
9425 asm_statement->clobbers = parse_asm_clobbers();
9428 rem_anchor_token(')');
9432 if (asm_statement->outputs == NULL) {
9433 /* GCC: An 'asm' instruction without any output operands will be treated
9434 * identically to a volatile 'asm' instruction. */
9435 asm_statement->is_volatile = true;
9440 return create_invalid_statement();
9444 * Parse a case statement.
9446 static statement_t *parse_case_statement(void)
9448 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9449 source_position_t *const pos = &statement->base.source_position;
9453 expression_t *const expression = parse_expression();
9454 statement->case_label.expression = expression;
9455 if (!is_constant_expression(expression)) {
9456 /* This check does not prevent the error message in all cases of an
9457 * prior error while parsing the expression. At least it catches the
9458 * common case of a mistyped enum entry. */
9459 if (is_type_valid(skip_typeref(expression->base.type))) {
9460 errorf(pos, "case label does not reduce to an integer constant");
9462 statement->case_label.is_bad = true;
9464 long const val = fold_constant(expression);
9465 statement->case_label.first_case = val;
9466 statement->case_label.last_case = val;
9470 if (token.type == T_DOTDOTDOT) {
9472 expression_t *const end_range = parse_expression();
9473 statement->case_label.end_range = end_range;
9474 if (!is_constant_expression(end_range)) {
9475 /* This check does not prevent the error message in all cases of an
9476 * prior error while parsing the expression. At least it catches the
9477 * common case of a mistyped enum entry. */
9478 if (is_type_valid(skip_typeref(end_range->base.type))) {
9479 errorf(pos, "case range does not reduce to an integer constant");
9481 statement->case_label.is_bad = true;
9483 long const val = fold_constant(end_range);
9484 statement->case_label.last_case = val;
9486 if (warning.other && val < statement->case_label.first_case) {
9487 statement->case_label.is_empty_range = true;
9488 warningf(pos, "empty range specified");
9494 PUSH_PARENT(statement);
9498 if (current_switch != NULL) {
9499 if (! statement->case_label.is_bad) {
9500 /* Check for duplicate case values */
9501 case_label_statement_t *c = &statement->case_label;
9502 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9503 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9506 if (c->last_case < l->first_case || c->first_case > l->last_case)
9509 errorf(pos, "duplicate case value (previously used %P)",
9510 &l->base.source_position);
9514 /* link all cases into the switch statement */
9515 if (current_switch->last_case == NULL) {
9516 current_switch->first_case = &statement->case_label;
9518 current_switch->last_case->next = &statement->case_label;
9520 current_switch->last_case = &statement->case_label;
9522 errorf(pos, "case label not within a switch statement");
9525 statement_t *const inner_stmt = parse_statement();
9526 statement->case_label.statement = inner_stmt;
9527 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9528 errorf(&inner_stmt->base.source_position, "declaration after case label");
9535 return create_invalid_statement();
9539 * Parse a default statement.
9541 static statement_t *parse_default_statement(void)
9543 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9547 PUSH_PARENT(statement);
9550 if (current_switch != NULL) {
9551 const case_label_statement_t *def_label = current_switch->default_label;
9552 if (def_label != NULL) {
9553 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9554 &def_label->base.source_position);
9556 current_switch->default_label = &statement->case_label;
9558 /* link all cases into the switch statement */
9559 if (current_switch->last_case == NULL) {
9560 current_switch->first_case = &statement->case_label;
9562 current_switch->last_case->next = &statement->case_label;
9564 current_switch->last_case = &statement->case_label;
9567 errorf(&statement->base.source_position,
9568 "'default' label not within a switch statement");
9571 statement_t *const inner_stmt = parse_statement();
9572 statement->case_label.statement = inner_stmt;
9573 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9574 errorf(&inner_stmt->base.source_position, "declaration after default label");
9581 return create_invalid_statement();
9585 * Parse a label statement.
9587 static statement_t *parse_label_statement(void)
9589 assert(token.type == T_IDENTIFIER);
9590 symbol_t *symbol = token.v.symbol;
9591 label_t *label = get_label(symbol);
9593 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9594 statement->label.label = label;
9598 PUSH_PARENT(statement);
9600 /* if statement is already set then the label is defined twice,
9601 * otherwise it was just mentioned in a goto/local label declaration so far
9603 if (label->statement != NULL) {
9604 errorf(HERE, "duplicate label '%Y' (declared %P)",
9605 symbol, &label->base.source_position);
9607 label->base.source_position = token.source_position;
9608 label->statement = statement;
9613 if (token.type == '}') {
9614 /* TODO only warn? */
9615 if (warning.other && false) {
9616 warningf(HERE, "label at end of compound statement");
9617 statement->label.statement = create_empty_statement();
9619 errorf(HERE, "label at end of compound statement");
9620 statement->label.statement = create_invalid_statement();
9622 } else if (token.type == ';') {
9623 /* Eat an empty statement here, to avoid the warning about an empty
9624 * statement after a label. label:; is commonly used to have a label
9625 * before a closing brace. */
9626 statement->label.statement = create_empty_statement();
9629 statement_t *const inner_stmt = parse_statement();
9630 statement->label.statement = inner_stmt;
9631 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9632 errorf(&inner_stmt->base.source_position, "declaration after label");
9636 /* remember the labels in a list for later checking */
9637 *label_anchor = &statement->label;
9638 label_anchor = &statement->label.next;
9645 * Parse an if statement.
9647 static statement_t *parse_if(void)
9649 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9653 PUSH_PARENT(statement);
9655 add_anchor_token('{');
9658 add_anchor_token(')');
9659 expression_t *const expr = parse_expression();
9660 statement->ifs.condition = expr;
9661 warn_reference_address_as_bool(expr);
9662 mark_vars_read(expr, NULL);
9663 rem_anchor_token(')');
9667 rem_anchor_token('{');
9669 add_anchor_token(T_else);
9670 statement->ifs.true_statement = parse_statement();
9671 rem_anchor_token(T_else);
9673 if (token.type == T_else) {
9675 statement->ifs.false_statement = parse_statement();
9683 * Check that all enums are handled in a switch.
9685 * @param statement the switch statement to check
9687 static void check_enum_cases(const switch_statement_t *statement) {
9688 const type_t *type = skip_typeref(statement->expression->base.type);
9689 if (! is_type_enum(type))
9691 const enum_type_t *enumt = &type->enumt;
9693 /* if we have a default, no warnings */
9694 if (statement->default_label != NULL)
9697 /* FIXME: calculation of value should be done while parsing */
9698 /* TODO: quadratic algorithm here. Change to an n log n one */
9699 long last_value = -1;
9700 const entity_t *entry = enumt->enume->base.next;
9701 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9702 entry = entry->base.next) {
9703 const expression_t *expression = entry->enum_value.value;
9704 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9706 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9707 if (l->expression == NULL)
9709 if (l->first_case <= value && value <= l->last_case) {
9715 warningf(&statement->base.source_position,
9716 "enumeration value '%Y' not handled in switch",
9717 entry->base.symbol);
9724 * Parse a switch statement.
9726 static statement_t *parse_switch(void)
9728 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9732 PUSH_PARENT(statement);
9735 add_anchor_token(')');
9736 expression_t *const expr = parse_expression();
9737 mark_vars_read(expr, NULL);
9738 type_t * type = skip_typeref(expr->base.type);
9739 if (is_type_integer(type)) {
9740 type = promote_integer(type);
9741 if (warning.traditional) {
9742 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9743 warningf(&expr->base.source_position,
9744 "'%T' switch expression not converted to '%T' in ISO C",
9748 } else if (is_type_valid(type)) {
9749 errorf(&expr->base.source_position,
9750 "switch quantity is not an integer, but '%T'", type);
9751 type = type_error_type;
9753 statement->switchs.expression = create_implicit_cast(expr, type);
9755 rem_anchor_token(')');
9757 switch_statement_t *rem = current_switch;
9758 current_switch = &statement->switchs;
9759 statement->switchs.body = parse_statement();
9760 current_switch = rem;
9762 if (warning.switch_default &&
9763 statement->switchs.default_label == NULL) {
9764 warningf(&statement->base.source_position, "switch has no default case");
9766 if (warning.switch_enum)
9767 check_enum_cases(&statement->switchs);
9773 return create_invalid_statement();
9776 static statement_t *parse_loop_body(statement_t *const loop)
9778 statement_t *const rem = current_loop;
9779 current_loop = loop;
9781 statement_t *const body = parse_statement();
9788 * Parse a while statement.
9790 static statement_t *parse_while(void)
9792 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9796 PUSH_PARENT(statement);
9799 add_anchor_token(')');
9800 expression_t *const cond = parse_expression();
9801 statement->whiles.condition = cond;
9802 warn_reference_address_as_bool(cond);
9803 mark_vars_read(cond, NULL);
9804 rem_anchor_token(')');
9807 statement->whiles.body = parse_loop_body(statement);
9813 return create_invalid_statement();
9817 * Parse a do statement.
9819 static statement_t *parse_do(void)
9821 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9825 PUSH_PARENT(statement);
9827 add_anchor_token(T_while);
9828 statement->do_while.body = parse_loop_body(statement);
9829 rem_anchor_token(T_while);
9833 add_anchor_token(')');
9834 expression_t *const cond = parse_expression();
9835 statement->do_while.condition = cond;
9836 warn_reference_address_as_bool(cond);
9837 mark_vars_read(cond, NULL);
9838 rem_anchor_token(')');
9846 return create_invalid_statement();
9850 * Parse a for statement.
9852 static statement_t *parse_for(void)
9854 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9858 PUSH_PARENT(statement);
9860 size_t const top = environment_top();
9861 scope_push(&statement->fors.scope);
9864 add_anchor_token(')');
9866 if (token.type != ';') {
9867 if (is_declaration_specifier(&token, false)) {
9868 parse_declaration(record_entity);
9870 add_anchor_token(';');
9871 expression_t *const init = parse_expression();
9872 statement->fors.initialisation = init;
9873 mark_vars_read(init, VAR_ANY);
9874 if (warning.unused_value && !expression_has_effect(init)) {
9875 warningf(&init->base.source_position,
9876 "initialisation of 'for'-statement has no effect");
9878 rem_anchor_token(';');
9885 if (token.type != ';') {
9886 add_anchor_token(';');
9887 expression_t *const cond = parse_expression();
9888 statement->fors.condition = cond;
9889 warn_reference_address_as_bool(cond);
9890 mark_vars_read(cond, NULL);
9891 rem_anchor_token(';');
9894 if (token.type != ')') {
9895 expression_t *const step = parse_expression();
9896 statement->fors.step = step;
9897 mark_vars_read(step, VAR_ANY);
9898 if (warning.unused_value && !expression_has_effect(step)) {
9899 warningf(&step->base.source_position,
9900 "step of 'for'-statement has no effect");
9904 rem_anchor_token(')');
9905 statement->fors.body = parse_loop_body(statement);
9907 assert(current_scope == &statement->fors.scope);
9909 environment_pop_to(top);
9916 rem_anchor_token(')');
9917 assert(current_scope == &statement->fors.scope);
9919 environment_pop_to(top);
9921 return create_invalid_statement();
9925 * Parse a goto statement.
9927 static statement_t *parse_goto(void)
9929 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9932 if (GNU_MODE && token.type == '*') {
9934 expression_t *expression = parse_expression();
9935 mark_vars_read(expression, NULL);
9937 /* Argh: although documentation says the expression must be of type void*,
9938 * gcc accepts anything that can be casted into void* without error */
9939 type_t *type = expression->base.type;
9941 if (type != type_error_type) {
9942 if (!is_type_pointer(type) && !is_type_integer(type)) {
9943 errorf(&expression->base.source_position,
9944 "cannot convert to a pointer type");
9945 } else if (warning.other && type != type_void_ptr) {
9946 warningf(&expression->base.source_position,
9947 "type of computed goto expression should be 'void*' not '%T'", type);
9949 expression = create_implicit_cast(expression, type_void_ptr);
9952 statement->gotos.expression = expression;
9954 if (token.type != T_IDENTIFIER) {
9956 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9958 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9962 symbol_t *symbol = token.v.symbol;
9965 statement->gotos.label = get_label(symbol);
9968 /* remember the goto's in a list for later checking */
9969 *goto_anchor = &statement->gotos;
9970 goto_anchor = &statement->gotos.next;
9976 return create_invalid_statement();
9980 * Parse a continue statement.
9982 static statement_t *parse_continue(void)
9984 if (current_loop == NULL) {
9985 errorf(HERE, "continue statement not within loop");
9988 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9998 * Parse a break statement.
10000 static statement_t *parse_break(void)
10002 if (current_switch == NULL && current_loop == NULL) {
10003 errorf(HERE, "break statement not within loop or switch");
10006 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10016 * Parse a __leave statement.
10018 static statement_t *parse_leave_statement(void)
10020 if (current_try == NULL) {
10021 errorf(HERE, "__leave statement not within __try");
10024 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10034 * Check if a given entity represents a local variable.
10036 static bool is_local_variable(const entity_t *entity)
10038 if (entity->kind != ENTITY_VARIABLE)
10041 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10042 case STORAGE_CLASS_AUTO:
10043 case STORAGE_CLASS_REGISTER: {
10044 const type_t *type = skip_typeref(entity->declaration.type);
10045 if (is_type_function(type)) {
10057 * Check if a given expression represents a local variable.
10059 static bool expression_is_local_variable(const expression_t *expression)
10061 if (expression->base.kind != EXPR_REFERENCE) {
10064 const entity_t *entity = expression->reference.entity;
10065 return is_local_variable(entity);
10069 * Check if a given expression represents a local variable and
10070 * return its declaration then, else return NULL.
10072 entity_t *expression_is_variable(const expression_t *expression)
10074 if (expression->base.kind != EXPR_REFERENCE) {
10077 entity_t *entity = expression->reference.entity;
10078 if (entity->kind != ENTITY_VARIABLE)
10085 * Parse a return statement.
10087 static statement_t *parse_return(void)
10091 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10093 expression_t *return_value = NULL;
10094 if (token.type != ';') {
10095 return_value = parse_expression();
10096 mark_vars_read(return_value, NULL);
10099 const type_t *const func_type = skip_typeref(current_function->base.type);
10100 assert(is_type_function(func_type));
10101 type_t *const return_type = skip_typeref(func_type->function.return_type);
10103 if (return_value != NULL) {
10104 type_t *return_value_type = skip_typeref(return_value->base.type);
10106 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10107 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10108 if (warning.other) {
10109 warningf(&statement->base.source_position,
10110 "'return' with a value, in function returning void");
10112 return_value = NULL;
10114 assign_error_t error = semantic_assign(return_type, return_value);
10115 report_assign_error(error, return_type, return_value, "'return'",
10116 &statement->base.source_position);
10117 return_value = create_implicit_cast(return_value, return_type);
10119 /* check for returning address of a local var */
10120 if (warning.other && return_value != NULL
10121 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10122 const expression_t *expression = return_value->unary.value;
10123 if (expression_is_local_variable(expression)) {
10124 warningf(&statement->base.source_position,
10125 "function returns address of local variable");
10128 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10129 warningf(&statement->base.source_position,
10130 "'return' without value, in function returning non-void");
10132 statement->returns.value = return_value;
10141 * Parse a declaration statement.
10143 static statement_t *parse_declaration_statement(void)
10145 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10147 entity_t *before = current_scope->last_entity;
10149 parse_external_declaration();
10151 parse_declaration(record_entity);
10153 if (before == NULL) {
10154 statement->declaration.declarations_begin = current_scope->entities;
10156 statement->declaration.declarations_begin = before->base.next;
10158 statement->declaration.declarations_end = current_scope->last_entity;
10164 * Parse an expression statement, ie. expr ';'.
10166 static statement_t *parse_expression_statement(void)
10168 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10170 expression_t *const expr = parse_expression();
10171 statement->expression.expression = expr;
10172 mark_vars_read(expr, VAR_ANY);
10181 * Parse a microsoft __try { } __finally { } or
10182 * __try{ } __except() { }
10184 static statement_t *parse_ms_try_statment(void)
10186 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10189 PUSH_PARENT(statement);
10191 ms_try_statement_t *rem = current_try;
10192 current_try = &statement->ms_try;
10193 statement->ms_try.try_statement = parse_compound_statement(false);
10198 if (token.type == T___except) {
10201 add_anchor_token(')');
10202 expression_t *const expr = parse_expression();
10203 mark_vars_read(expr, NULL);
10204 type_t * type = skip_typeref(expr->base.type);
10205 if (is_type_integer(type)) {
10206 type = promote_integer(type);
10207 } else if (is_type_valid(type)) {
10208 errorf(&expr->base.source_position,
10209 "__expect expression is not an integer, but '%T'", type);
10210 type = type_error_type;
10212 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10213 rem_anchor_token(')');
10215 statement->ms_try.final_statement = parse_compound_statement(false);
10216 } else if (token.type == T__finally) {
10218 statement->ms_try.final_statement = parse_compound_statement(false);
10220 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10221 return create_invalid_statement();
10225 return create_invalid_statement();
10228 static statement_t *parse_empty_statement(void)
10230 if (warning.empty_statement) {
10231 warningf(HERE, "statement is empty");
10233 statement_t *const statement = create_empty_statement();
10238 static statement_t *parse_local_label_declaration(void)
10240 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10244 entity_t *begin = NULL, *end = NULL;
10247 if (token.type != T_IDENTIFIER) {
10248 parse_error_expected("while parsing local label declaration",
10249 T_IDENTIFIER, NULL);
10252 symbol_t *symbol = token.v.symbol;
10253 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10254 if (entity != NULL && entity->base.parent_scope == current_scope) {
10255 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10256 symbol, &entity->base.source_position);
10258 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10260 entity->base.parent_scope = current_scope;
10261 entity->base.namespc = NAMESPACE_LABEL;
10262 entity->base.source_position = token.source_position;
10263 entity->base.symbol = symbol;
10266 end->base.next = entity;
10271 environment_push(entity);
10275 if (token.type != ',')
10281 statement->declaration.declarations_begin = begin;
10282 statement->declaration.declarations_end = end;
10286 static void parse_namespace_definition(void)
10290 entity_t *entity = NULL;
10291 symbol_t *symbol = NULL;
10293 if (token.type == T_IDENTIFIER) {
10294 symbol = token.v.symbol;
10297 entity = get_entity(symbol, NAMESPACE_NORMAL);
10298 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10299 && entity->base.parent_scope == current_scope) {
10300 error_redefined_as_different_kind(&token.source_position,
10301 entity, ENTITY_NAMESPACE);
10306 if (entity == NULL) {
10307 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10308 entity->base.symbol = symbol;
10309 entity->base.source_position = token.source_position;
10310 entity->base.namespc = NAMESPACE_NORMAL;
10311 entity->base.parent_scope = current_scope;
10314 if (token.type == '=') {
10315 /* TODO: parse namespace alias */
10316 panic("namespace alias definition not supported yet");
10319 environment_push(entity);
10320 append_entity(current_scope, entity);
10322 size_t const top = environment_top();
10323 scope_push(&entity->namespacee.members);
10330 assert(current_scope == &entity->namespacee.members);
10332 environment_pop_to(top);
10336 * Parse a statement.
10337 * There's also parse_statement() which additionally checks for
10338 * "statement has no effect" warnings
10340 static statement_t *intern_parse_statement(void)
10342 statement_t *statement = NULL;
10344 /* declaration or statement */
10345 add_anchor_token(';');
10346 switch (token.type) {
10347 case T_IDENTIFIER: {
10348 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10349 if (la1_type == ':') {
10350 statement = parse_label_statement();
10351 } else if (is_typedef_symbol(token.v.symbol)) {
10352 statement = parse_declaration_statement();
10354 /* it's an identifier, the grammar says this must be an
10355 * expression statement. However it is common that users mistype
10356 * declaration types, so we guess a bit here to improve robustness
10357 * for incorrect programs */
10358 switch (la1_type) {
10361 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10362 goto expression_statment;
10367 statement = parse_declaration_statement();
10371 expression_statment:
10372 statement = parse_expression_statement();
10379 case T___extension__:
10380 /* This can be a prefix to a declaration or an expression statement.
10381 * We simply eat it now and parse the rest with tail recursion. */
10384 } while (token.type == T___extension__);
10385 bool old_gcc_extension = in_gcc_extension;
10386 in_gcc_extension = true;
10387 statement = parse_statement();
10388 in_gcc_extension = old_gcc_extension;
10392 statement = parse_declaration_statement();
10396 statement = parse_local_label_declaration();
10399 case ';': statement = parse_empty_statement(); break;
10400 case '{': statement = parse_compound_statement(false); break;
10401 case T___leave: statement = parse_leave_statement(); break;
10402 case T___try: statement = parse_ms_try_statment(); break;
10403 case T_asm: statement = parse_asm_statement(); break;
10404 case T_break: statement = parse_break(); break;
10405 case T_case: statement = parse_case_statement(); break;
10406 case T_continue: statement = parse_continue(); break;
10407 case T_default: statement = parse_default_statement(); break;
10408 case T_do: statement = parse_do(); break;
10409 case T_for: statement = parse_for(); break;
10410 case T_goto: statement = parse_goto(); break;
10411 case T_if: statement = parse_if(); break;
10412 case T_return: statement = parse_return(); break;
10413 case T_switch: statement = parse_switch(); break;
10414 case T_while: statement = parse_while(); break;
10417 statement = parse_expression_statement();
10421 errorf(HERE, "unexpected token %K while parsing statement", &token);
10422 statement = create_invalid_statement();
10427 rem_anchor_token(';');
10429 assert(statement != NULL
10430 && statement->base.source_position.input_name != NULL);
10436 * parse a statement and emits "statement has no effect" warning if needed
10437 * (This is really a wrapper around intern_parse_statement with check for 1
10438 * single warning. It is needed, because for statement expressions we have
10439 * to avoid the warning on the last statement)
10441 static statement_t *parse_statement(void)
10443 statement_t *statement = intern_parse_statement();
10445 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10446 expression_t *expression = statement->expression.expression;
10447 if (!expression_has_effect(expression)) {
10448 warningf(&expression->base.source_position,
10449 "statement has no effect");
10457 * Parse a compound statement.
10459 static statement_t *parse_compound_statement(bool inside_expression_statement)
10461 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10463 PUSH_PARENT(statement);
10466 add_anchor_token('}');
10468 size_t const top = environment_top();
10469 scope_push(&statement->compound.scope);
10471 statement_t **anchor = &statement->compound.statements;
10472 bool only_decls_so_far = true;
10473 while (token.type != '}') {
10474 if (token.type == T_EOF) {
10475 errorf(&statement->base.source_position,
10476 "EOF while parsing compound statement");
10479 statement_t *sub_statement = intern_parse_statement();
10480 if (is_invalid_statement(sub_statement)) {
10481 /* an error occurred. if we are at an anchor, return */
10487 if (warning.declaration_after_statement) {
10488 if (sub_statement->kind != STATEMENT_DECLARATION) {
10489 only_decls_so_far = false;
10490 } else if (!only_decls_so_far) {
10491 warningf(&sub_statement->base.source_position,
10492 "ISO C90 forbids mixed declarations and code");
10496 *anchor = sub_statement;
10498 while (sub_statement->base.next != NULL)
10499 sub_statement = sub_statement->base.next;
10501 anchor = &sub_statement->base.next;
10505 /* look over all statements again to produce no effect warnings */
10506 if (warning.unused_value) {
10507 statement_t *sub_statement = statement->compound.statements;
10508 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10509 if (sub_statement->kind != STATEMENT_EXPRESSION)
10511 /* don't emit a warning for the last expression in an expression
10512 * statement as it has always an effect */
10513 if (inside_expression_statement && sub_statement->base.next == NULL)
10516 expression_t *expression = sub_statement->expression.expression;
10517 if (!expression_has_effect(expression)) {
10518 warningf(&expression->base.source_position,
10519 "statement has no effect");
10525 rem_anchor_token('}');
10526 assert(current_scope == &statement->compound.scope);
10528 environment_pop_to(top);
10535 * Check for unused global static functions and variables
10537 static void check_unused_globals(void)
10539 if (!warning.unused_function && !warning.unused_variable)
10542 for (const entity_t *entity = file_scope->entities; entity != NULL;
10543 entity = entity->base.next) {
10544 if (!is_declaration(entity))
10547 const declaration_t *declaration = &entity->declaration;
10548 if (declaration->used ||
10549 declaration->modifiers & DM_UNUSED ||
10550 declaration->modifiers & DM_USED ||
10551 declaration->storage_class != STORAGE_CLASS_STATIC)
10554 type_t *const type = declaration->type;
10556 if (entity->kind == ENTITY_FUNCTION) {
10557 /* inhibit warning for static inline functions */
10558 if (entity->function.is_inline)
10561 s = entity->function.statement != NULL ? "defined" : "declared";
10566 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10567 type, declaration->base.symbol, s);
10571 static void parse_global_asm(void)
10573 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10578 statement->asms.asm_text = parse_string_literals();
10579 statement->base.next = unit->global_asm;
10580 unit->global_asm = statement;
10588 static void parse_linkage_specification(void)
10591 assert(token.type == T_STRING_LITERAL);
10593 const char *linkage = parse_string_literals().begin;
10595 linkage_kind_t old_linkage = current_linkage;
10596 linkage_kind_t new_linkage;
10597 if (strcmp(linkage, "C") == 0) {
10598 new_linkage = LINKAGE_C;
10599 } else if (strcmp(linkage, "C++") == 0) {
10600 new_linkage = LINKAGE_CXX;
10602 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10603 new_linkage = LINKAGE_INVALID;
10605 current_linkage = new_linkage;
10607 if (token.type == '{') {
10616 assert(current_linkage == new_linkage);
10617 current_linkage = old_linkage;
10620 static void parse_external(void)
10622 switch (token.type) {
10623 DECLARATION_START_NO_EXTERN
10625 case T___extension__:
10626 case '(': /* for function declarations with implicit return type and
10627 * parenthesized declarator, i.e. (f)(void); */
10628 parse_external_declaration();
10632 if (look_ahead(1)->type == T_STRING_LITERAL) {
10633 parse_linkage_specification();
10635 parse_external_declaration();
10640 parse_global_asm();
10644 parse_namespace_definition();
10648 if (!strict_mode) {
10650 warningf(HERE, "stray ';' outside of function");
10657 errorf(HERE, "stray %K outside of function", &token);
10658 if (token.type == '(' || token.type == '{' || token.type == '[')
10659 eat_until_matching_token(token.type);
10665 static void parse_externals(void)
10667 add_anchor_token('}');
10668 add_anchor_token(T_EOF);
10671 unsigned char token_anchor_copy[T_LAST_TOKEN];
10672 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10675 while (token.type != T_EOF && token.type != '}') {
10677 bool anchor_leak = false;
10678 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10679 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10681 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10682 anchor_leak = true;
10685 if (in_gcc_extension) {
10686 errorf(HERE, "Leaked __extension__");
10687 anchor_leak = true;
10697 rem_anchor_token(T_EOF);
10698 rem_anchor_token('}');
10702 * Parse a translation unit.
10704 static void parse_translation_unit(void)
10706 add_anchor_token(T_EOF);
10711 if (token.type == T_EOF)
10714 errorf(HERE, "stray %K outside of function", &token);
10715 if (token.type == '(' || token.type == '{' || token.type == '[')
10716 eat_until_matching_token(token.type);
10724 * @return the translation unit or NULL if errors occurred.
10726 void start_parsing(void)
10728 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10729 label_stack = NEW_ARR_F(stack_entry_t, 0);
10730 diagnostic_count = 0;
10734 type_set_output(stderr);
10735 ast_set_output(stderr);
10737 assert(unit == NULL);
10738 unit = allocate_ast_zero(sizeof(unit[0]));
10740 assert(file_scope == NULL);
10741 file_scope = &unit->scope;
10743 assert(current_scope == NULL);
10744 scope_push(&unit->scope);
10747 translation_unit_t *finish_parsing(void)
10749 /* do NOT use scope_pop() here, this will crash, will it by hand */
10750 assert(current_scope == &unit->scope);
10751 current_scope = NULL;
10753 assert(file_scope == &unit->scope);
10754 check_unused_globals();
10757 DEL_ARR_F(environment_stack);
10758 DEL_ARR_F(label_stack);
10760 translation_unit_t *result = unit;
10767 lookahead_bufpos = 0;
10768 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10771 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10772 parse_translation_unit();
10776 * Initialize the parser.
10778 void init_parser(void)
10780 sym_anonymous = symbol_table_insert("<anonymous>");
10782 if (c_mode & _MS) {
10783 /* add predefined symbols for extended-decl-modifier */
10784 sym_align = symbol_table_insert("align");
10785 sym_allocate = symbol_table_insert("allocate");
10786 sym_dllimport = symbol_table_insert("dllimport");
10787 sym_dllexport = symbol_table_insert("dllexport");
10788 sym_naked = symbol_table_insert("naked");
10789 sym_noinline = symbol_table_insert("noinline");
10790 sym_noreturn = symbol_table_insert("noreturn");
10791 sym_nothrow = symbol_table_insert("nothrow");
10792 sym_novtable = symbol_table_insert("novtable");
10793 sym_property = symbol_table_insert("property");
10794 sym_get = symbol_table_insert("get");
10795 sym_put = symbol_table_insert("put");
10796 sym_selectany = symbol_table_insert("selectany");
10797 sym_thread = symbol_table_insert("thread");
10798 sym_uuid = symbol_table_insert("uuid");
10799 sym_deprecated = symbol_table_insert("deprecated");
10800 sym_restrict = symbol_table_insert("restrict");
10801 sym_noalias = symbol_table_insert("noalias");
10803 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10805 init_expression_parsers();
10806 obstack_init(&temp_obst);
10808 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10809 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10813 * Terminate the parser.
10815 void exit_parser(void)
10817 obstack_free(&temp_obst, NULL);