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 an incompatible type.
750 static void type_error_incompatible(const char *msg,
751 const source_position_t *source_position, type_t *type1, type_t *type2)
753 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
758 * Expect the the current token is the expected token.
759 * If not, generate an error, eat the current statement,
760 * and goto the end_error label.
762 #define expect(expected) \
764 if (UNLIKELY(token.type != (expected))) { \
765 parse_error_expected(NULL, (expected), NULL); \
766 add_anchor_token(expected); \
767 eat_until_anchor(); \
768 if (token.type == expected) \
770 rem_anchor_token(expected); \
776 static void scope_push(scope_t *new_scope)
778 if (current_scope != NULL) {
779 new_scope->depth = current_scope->depth + 1;
781 new_scope->parent = current_scope;
782 current_scope = new_scope;
785 static void scope_pop(void)
787 current_scope = current_scope->parent;
791 * Search an entity by its symbol in a given namespace.
793 static entity_t *get_entity(const symbol_t *const symbol,
794 namespace_tag_t namespc)
796 entity_t *entity = symbol->entity;
797 for (; entity != NULL; entity = entity->base.symbol_next) {
798 if (entity->base.namespc == namespc)
806 * pushs an entity on the environment stack and links the corresponding symbol
809 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
811 symbol_t *symbol = entity->base.symbol;
812 entity_namespace_t namespc = entity->base.namespc;
813 assert(namespc != NAMESPACE_INVALID);
815 /* replace/add entity into entity list of the symbol */
818 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
823 /* replace an entry? */
824 if (iter->base.namespc == namespc) {
825 entity->base.symbol_next = iter->base.symbol_next;
831 /* remember old declaration */
833 entry.symbol = symbol;
834 entry.old_entity = iter;
835 entry.namespc = namespc;
836 ARR_APP1(stack_entry_t, *stack_ptr, entry);
840 * Push an entity on the environment stack.
842 static void environment_push(entity_t *entity)
844 assert(entity->base.source_position.input_name != NULL);
845 assert(entity->base.parent_scope != NULL);
846 stack_push(&environment_stack, entity);
850 * Push a declaration on the global label stack.
852 * @param declaration the declaration
854 static void label_push(entity_t *label)
856 /* we abuse the parameters scope as parent for the labels */
857 label->base.parent_scope = ¤t_function->parameters;
858 stack_push(&label_stack, label);
862 * pops symbols from the environment stack until @p new_top is the top element
864 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
866 stack_entry_t *stack = *stack_ptr;
867 size_t top = ARR_LEN(stack);
870 assert(new_top <= top);
874 for (i = top; i > new_top; --i) {
875 stack_entry_t *entry = &stack[i - 1];
877 entity_t *old_entity = entry->old_entity;
878 symbol_t *symbol = entry->symbol;
879 entity_namespace_t namespc = entry->namespc;
881 /* replace with old_entity/remove */
884 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
886 assert(iter != NULL);
887 /* replace an entry? */
888 if (iter->base.namespc == namespc)
892 /* restore definition from outer scopes (if there was one) */
893 if (old_entity != NULL) {
894 old_entity->base.symbol_next = iter->base.symbol_next;
895 *anchor = old_entity;
897 /* remove entry from list */
898 *anchor = iter->base.symbol_next;
902 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
906 * Pop all entries from the environment stack until the new_top
909 * @param new_top the new stack top
911 static void environment_pop_to(size_t new_top)
913 stack_pop_to(&environment_stack, new_top);
917 * Pop all entries from the global label stack until the new_top
920 * @param new_top the new stack top
922 static void label_pop_to(size_t new_top)
924 stack_pop_to(&label_stack, new_top);
927 static int get_akind_rank(atomic_type_kind_t akind)
932 static int get_rank(const type_t *type)
934 assert(!is_typeref(type));
935 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
936 * and esp. footnote 108). However we can't fold constants (yet), so we
937 * can't decide whether unsigned int is possible, while int always works.
938 * (unsigned int would be preferable when possible... for stuff like
939 * struct { enum { ... } bla : 4; } ) */
940 if (type->kind == TYPE_ENUM)
941 return get_akind_rank(ATOMIC_TYPE_INT);
943 assert(type->kind == TYPE_ATOMIC);
944 return get_akind_rank(type->atomic.akind);
947 static type_t *promote_integer(type_t *type)
949 if (type->kind == TYPE_BITFIELD)
950 type = type->bitfield.base_type;
952 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
959 * Create a cast expression.
961 * @param expression the expression to cast
962 * @param dest_type the destination type
964 static expression_t *create_cast_expression(expression_t *expression,
967 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
969 cast->unary.value = expression;
970 cast->base.type = dest_type;
976 * Check if a given expression represents the 0 pointer constant.
978 static bool is_null_pointer_constant(const expression_t *expression)
980 /* skip void* cast */
981 if (expression->kind == EXPR_UNARY_CAST
982 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
983 expression = expression->unary.value;
986 /* TODO: not correct yet, should be any constant integer expression
987 * which evaluates to 0 */
988 if (expression->kind != EXPR_CONST)
991 type_t *const type = skip_typeref(expression->base.type);
992 if (!is_type_integer(type))
995 return expression->conste.v.int_value == 0;
999 * Create an implicit cast expression.
1001 * @param expression the expression to cast
1002 * @param dest_type the destination type
1004 static expression_t *create_implicit_cast(expression_t *expression,
1007 type_t *const source_type = expression->base.type;
1009 if (source_type == dest_type)
1012 return create_cast_expression(expression, dest_type);
1015 typedef enum assign_error_t {
1017 ASSIGN_ERROR_INCOMPATIBLE,
1018 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1019 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1020 ASSIGN_WARNING_POINTER_FROM_INT,
1021 ASSIGN_WARNING_INT_FROM_POINTER
1024 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1025 const expression_t *const right,
1026 const char *context,
1027 const source_position_t *source_position)
1029 type_t *const orig_type_right = right->base.type;
1030 type_t *const type_left = skip_typeref(orig_type_left);
1031 type_t *const type_right = skip_typeref(orig_type_right);
1034 case ASSIGN_SUCCESS:
1036 case ASSIGN_ERROR_INCOMPATIBLE:
1037 errorf(source_position,
1038 "destination type '%T' in %s is incompatible with type '%T'",
1039 orig_type_left, context, orig_type_right);
1042 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1043 if (warning.other) {
1044 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1045 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1047 /* the left type has all qualifiers from the right type */
1048 unsigned missing_qualifiers
1049 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1050 warningf(source_position,
1051 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1052 orig_type_left, context, orig_type_right, missing_qualifiers);
1057 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1058 if (warning.other) {
1059 warningf(source_position,
1060 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1061 orig_type_left, context, right, orig_type_right);
1065 case ASSIGN_WARNING_POINTER_FROM_INT:
1066 if (warning.other) {
1067 warningf(source_position,
1068 "%s makes pointer '%T' from integer '%T' without a cast",
1069 context, orig_type_left, orig_type_right);
1073 case ASSIGN_WARNING_INT_FROM_POINTER:
1074 if (warning.other) {
1075 warningf(source_position,
1076 "%s makes integer '%T' from pointer '%T' without a cast",
1077 context, orig_type_left, orig_type_right);
1082 panic("invalid error value");
1086 /** Implements the rules from § 6.5.16.1 */
1087 static assign_error_t semantic_assign(type_t *orig_type_left,
1088 const expression_t *const right)
1090 type_t *const orig_type_right = right->base.type;
1091 type_t *const type_left = skip_typeref(orig_type_left);
1092 type_t *const type_right = skip_typeref(orig_type_right);
1094 if (is_type_pointer(type_left)) {
1095 if (is_null_pointer_constant(right)) {
1096 return ASSIGN_SUCCESS;
1097 } else if (is_type_pointer(type_right)) {
1098 type_t *points_to_left
1099 = skip_typeref(type_left->pointer.points_to);
1100 type_t *points_to_right
1101 = skip_typeref(type_right->pointer.points_to);
1102 assign_error_t res = ASSIGN_SUCCESS;
1104 /* the left type has all qualifiers from the right type */
1105 unsigned missing_qualifiers
1106 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1107 if (missing_qualifiers != 0) {
1108 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1111 points_to_left = get_unqualified_type(points_to_left);
1112 points_to_right = get_unqualified_type(points_to_right);
1114 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1117 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1118 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1119 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1122 if (!types_compatible(points_to_left, points_to_right)) {
1123 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1127 } else if (is_type_integer(type_right)) {
1128 return ASSIGN_WARNING_POINTER_FROM_INT;
1130 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1131 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1132 && is_type_pointer(type_right))) {
1133 return ASSIGN_SUCCESS;
1134 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1135 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1136 type_t *const unqual_type_left = get_unqualified_type(type_left);
1137 type_t *const unqual_type_right = get_unqualified_type(type_right);
1138 if (types_compatible(unqual_type_left, unqual_type_right)) {
1139 return ASSIGN_SUCCESS;
1141 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1142 return ASSIGN_WARNING_INT_FROM_POINTER;
1145 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1146 return ASSIGN_SUCCESS;
1148 return ASSIGN_ERROR_INCOMPATIBLE;
1151 static expression_t *parse_constant_expression(void)
1153 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1155 if (!is_constant_expression(result)) {
1156 errorf(&result->base.source_position,
1157 "expression '%E' is not constant\n", result);
1163 static expression_t *parse_assignment_expression(void)
1165 return parse_sub_expression(PREC_ASSIGNMENT);
1168 static string_t parse_string_literals(void)
1170 assert(token.type == T_STRING_LITERAL);
1171 string_t result = token.v.string;
1175 while (token.type == T_STRING_LITERAL) {
1176 result = concat_strings(&result, &token.v.string);
1183 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1184 [GNU_AK_CONST] = "const",
1185 [GNU_AK_VOLATILE] = "volatile",
1186 [GNU_AK_CDECL] = "cdecl",
1187 [GNU_AK_STDCALL] = "stdcall",
1188 [GNU_AK_FASTCALL] = "fastcall",
1189 [GNU_AK_DEPRECATED] = "deprecated",
1190 [GNU_AK_NOINLINE] = "noinline",
1191 [GNU_AK_NORETURN] = "noreturn",
1192 [GNU_AK_NAKED] = "naked",
1193 [GNU_AK_PURE] = "pure",
1194 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1195 [GNU_AK_MALLOC] = "malloc",
1196 [GNU_AK_WEAK] = "weak",
1197 [GNU_AK_CONSTRUCTOR] = "constructor",
1198 [GNU_AK_DESTRUCTOR] = "destructor",
1199 [GNU_AK_NOTHROW] = "nothrow",
1200 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1201 [GNU_AK_COMMON] = "common",
1202 [GNU_AK_NOCOMMON] = "nocommon",
1203 [GNU_AK_PACKED] = "packed",
1204 [GNU_AK_SHARED] = "shared",
1205 [GNU_AK_NOTSHARED] = "notshared",
1206 [GNU_AK_USED] = "used",
1207 [GNU_AK_UNUSED] = "unused",
1208 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1209 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1210 [GNU_AK_LONGCALL] = "longcall",
1211 [GNU_AK_SHORTCALL] = "shortcall",
1212 [GNU_AK_LONG_CALL] = "long_call",
1213 [GNU_AK_SHORT_CALL] = "short_call",
1214 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1215 [GNU_AK_INTERRUPT] = "interrupt",
1216 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1217 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1218 [GNU_AK_NESTING] = "nesting",
1219 [GNU_AK_NEAR] = "near",
1220 [GNU_AK_FAR] = "far",
1221 [GNU_AK_SIGNAL] = "signal",
1222 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1223 [GNU_AK_TINY_DATA] = "tiny_data",
1224 [GNU_AK_SAVEALL] = "saveall",
1225 [GNU_AK_FLATTEN] = "flatten",
1226 [GNU_AK_SSEREGPARM] = "sseregparm",
1227 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1228 [GNU_AK_RETURN_TWICE] = "return_twice",
1229 [GNU_AK_MAY_ALIAS] = "may_alias",
1230 [GNU_AK_MS_STRUCT] = "ms_struct",
1231 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1232 [GNU_AK_DLLIMPORT] = "dllimport",
1233 [GNU_AK_DLLEXPORT] = "dllexport",
1234 [GNU_AK_ALIGNED] = "aligned",
1235 [GNU_AK_ALIAS] = "alias",
1236 [GNU_AK_SECTION] = "section",
1237 [GNU_AK_FORMAT] = "format",
1238 [GNU_AK_FORMAT_ARG] = "format_arg",
1239 [GNU_AK_WEAKREF] = "weakref",
1240 [GNU_AK_NONNULL] = "nonnull",
1241 [GNU_AK_TLS_MODEL] = "tls_model",
1242 [GNU_AK_VISIBILITY] = "visibility",
1243 [GNU_AK_REGPARM] = "regparm",
1244 [GNU_AK_MODE] = "mode",
1245 [GNU_AK_MODEL] = "model",
1246 [GNU_AK_TRAP_EXIT] = "trap_exit",
1247 [GNU_AK_SP_SWITCH] = "sp_switch",
1248 [GNU_AK_SENTINEL] = "sentinel"
1252 * compare two string, ignoring double underscores on the second.
1254 static int strcmp_underscore(const char *s1, const char *s2)
1256 if (s2[0] == '_' && s2[1] == '_') {
1257 size_t len2 = strlen(s2);
1258 size_t len1 = strlen(s1);
1259 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1260 return strncmp(s1, s2+2, len2-4);
1264 return strcmp(s1, s2);
1268 * Allocate a new gnu temporal attribute.
1270 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1272 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1273 attribute->kind = kind;
1274 attribute->next = NULL;
1275 attribute->invalid = false;
1276 attribute->have_arguments = false;
1282 * parse one constant expression argument.
1284 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1286 expression_t *expression;
1287 add_anchor_token(')');
1288 expression = parse_constant_expression();
1289 rem_anchor_token(')');
1291 attribute->u.argument = fold_constant(expression);
1294 attribute->invalid = true;
1298 * parse a list of constant expressions arguments.
1300 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1302 argument_list_t **list = &attribute->u.arguments;
1303 argument_list_t *entry;
1304 expression_t *expression;
1305 add_anchor_token(')');
1306 add_anchor_token(',');
1308 expression = parse_constant_expression();
1309 entry = obstack_alloc(&temp_obst, sizeof(entry));
1310 entry->argument = fold_constant(expression);
1313 list = &entry->next;
1314 if (token.type != ',')
1318 rem_anchor_token(',');
1319 rem_anchor_token(')');
1323 attribute->invalid = true;
1327 * parse one string literal argument.
1329 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1332 add_anchor_token('(');
1333 if (token.type != T_STRING_LITERAL) {
1334 parse_error_expected("while parsing attribute directive",
1335 T_STRING_LITERAL, NULL);
1338 *string = parse_string_literals();
1339 rem_anchor_token('(');
1343 attribute->invalid = true;
1347 * parse one tls model.
1349 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1351 static const char *const tls_models[] = {
1357 string_t string = { NULL, 0 };
1358 parse_gnu_attribute_string_arg(attribute, &string);
1359 if (string.begin != NULL) {
1360 for (size_t i = 0; i < 4; ++i) {
1361 if (strcmp(tls_models[i], string.begin) == 0) {
1362 attribute->u.value = i;
1366 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1368 attribute->invalid = true;
1372 * parse one tls model.
1374 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1376 static const char *const visibilities[] = {
1382 string_t string = { NULL, 0 };
1383 parse_gnu_attribute_string_arg(attribute, &string);
1384 if (string.begin != NULL) {
1385 for (size_t i = 0; i < 4; ++i) {
1386 if (strcmp(visibilities[i], string.begin) == 0) {
1387 attribute->u.value = i;
1391 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1393 attribute->invalid = true;
1397 * parse one (code) model.
1399 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1401 static const char *const visibilities[] = {
1406 string_t string = { NULL, 0 };
1407 parse_gnu_attribute_string_arg(attribute, &string);
1408 if (string.begin != NULL) {
1409 for (int i = 0; i < 3; ++i) {
1410 if (strcmp(visibilities[i], string.begin) == 0) {
1411 attribute->u.value = i;
1415 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1417 attribute->invalid = true;
1420 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1422 /* TODO: find out what is allowed here... */
1424 /* at least: byte, word, pointer, list of machine modes
1425 * __XXX___ is interpreted as XXX */
1426 add_anchor_token(')');
1428 if (token.type != T_IDENTIFIER) {
1429 expect(T_IDENTIFIER);
1432 /* This isn't really correct, the backend should provide a list of machine
1433 * specific modes (according to gcc philosophy that is...) */
1434 const char *symbol_str = token.v.symbol->string;
1435 if (strcmp_underscore("QI", symbol_str) == 0 ||
1436 strcmp_underscore("byte", symbol_str) == 0) {
1437 attribute->u.akind = ATOMIC_TYPE_CHAR;
1438 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1439 attribute->u.akind = ATOMIC_TYPE_SHORT;
1440 } else if (strcmp_underscore("SI", symbol_str) == 0
1441 || strcmp_underscore("word", symbol_str) == 0
1442 || strcmp_underscore("pointer", symbol_str) == 0) {
1443 attribute->u.akind = ATOMIC_TYPE_INT;
1444 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1445 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1448 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1449 attribute->invalid = true;
1453 rem_anchor_token(')');
1457 attribute->invalid = true;
1461 * parse one interrupt argument.
1463 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1465 static const char *const interrupts[] = {
1472 string_t string = { NULL, 0 };
1473 parse_gnu_attribute_string_arg(attribute, &string);
1474 if (string.begin != NULL) {
1475 for (size_t i = 0; i < 5; ++i) {
1476 if (strcmp(interrupts[i], string.begin) == 0) {
1477 attribute->u.value = i;
1481 errorf(HERE, "'%s' is not an interrupt", string.begin);
1483 attribute->invalid = true;
1487 * parse ( identifier, const expression, const expression )
1489 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1491 static const char *const format_names[] = {
1499 if (token.type != T_IDENTIFIER) {
1500 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1503 const char *name = token.v.symbol->string;
1504 for (i = 0; i < 4; ++i) {
1505 if (strcmp_underscore(format_names[i], name) == 0)
1509 if (warning.attribute)
1510 warningf(HERE, "'%s' is an unrecognized format function type", name);
1515 add_anchor_token(')');
1516 add_anchor_token(',');
1517 parse_constant_expression();
1518 rem_anchor_token(',');
1519 rem_anchor_token(')');
1522 add_anchor_token(')');
1523 parse_constant_expression();
1524 rem_anchor_token(')');
1528 attribute->u.value = true;
1531 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1533 if (!attribute->have_arguments)
1536 /* should have no arguments */
1537 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1538 eat_until_matching_token('(');
1539 /* we have already consumed '(', so we stop before ')', eat it */
1541 attribute->invalid = true;
1545 * Parse one GNU attribute.
1547 * Note that attribute names can be specified WITH or WITHOUT
1548 * double underscores, ie const or __const__.
1550 * The following attributes are parsed without arguments
1575 * no_instrument_function
1576 * warn_unused_result
1593 * externally_visible
1601 * The following attributes are parsed with arguments
1602 * aligned( const expression )
1603 * alias( string literal )
1604 * section( string literal )
1605 * format( identifier, const expression, const expression )
1606 * format_arg( const expression )
1607 * tls_model( string literal )
1608 * visibility( string literal )
1609 * regparm( const expression )
1610 * model( string leteral )
1611 * trap_exit( const expression )
1612 * sp_switch( string literal )
1614 * The following attributes might have arguments
1615 * weak_ref( string literal )
1616 * non_null( const expression // ',' )
1617 * interrupt( string literal )
1618 * sentinel( constant expression )
1620 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1622 gnu_attribute_t *head = *attributes;
1623 gnu_attribute_t *last = *attributes;
1624 decl_modifiers_t modifiers = 0;
1625 gnu_attribute_t *attribute;
1627 eat(T___attribute__);
1631 if (token.type != ')') {
1632 /* find the end of the list */
1634 while (last->next != NULL)
1638 /* non-empty attribute list */
1641 if (token.type == T_const) {
1643 } else if (token.type == T_volatile) {
1645 } else if (token.type == T_cdecl) {
1646 /* __attribute__((cdecl)), WITH ms mode */
1648 } else if (token.type == T_IDENTIFIER) {
1649 const symbol_t *sym = token.v.symbol;
1652 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1659 for (i = 0; i < GNU_AK_LAST; ++i) {
1660 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1663 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1666 if (kind == GNU_AK_LAST) {
1667 if (warning.attribute)
1668 warningf(HERE, "'%s' attribute directive ignored", name);
1670 /* skip possible arguments */
1671 if (token.type == '(') {
1672 eat_until_matching_token(')');
1675 /* check for arguments */
1676 attribute = allocate_gnu_attribute(kind);
1677 if (token.type == '(') {
1679 if (token.type == ')') {
1680 /* empty args are allowed */
1683 attribute->have_arguments = true;
1687 case GNU_AK_VOLATILE:
1692 case GNU_AK_NOCOMMON:
1694 case GNU_AK_NOTSHARED:
1695 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1696 case GNU_AK_WARN_UNUSED_RESULT:
1697 case GNU_AK_LONGCALL:
1698 case GNU_AK_SHORTCALL:
1699 case GNU_AK_LONG_CALL:
1700 case GNU_AK_SHORT_CALL:
1701 case GNU_AK_FUNCTION_VECTOR:
1702 case GNU_AK_INTERRUPT_HANDLER:
1703 case GNU_AK_NMI_HANDLER:
1704 case GNU_AK_NESTING:
1708 case GNU_AK_EIGTHBIT_DATA:
1709 case GNU_AK_TINY_DATA:
1710 case GNU_AK_SAVEALL:
1711 case GNU_AK_FLATTEN:
1712 case GNU_AK_SSEREGPARM:
1713 case GNU_AK_EXTERNALLY_VISIBLE:
1714 case GNU_AK_RETURN_TWICE:
1715 case GNU_AK_MAY_ALIAS:
1716 case GNU_AK_MS_STRUCT:
1717 case GNU_AK_GCC_STRUCT:
1720 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1721 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1722 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1723 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1724 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1725 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1726 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1727 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1728 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1729 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1730 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1731 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1732 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1733 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1734 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1735 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1736 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1737 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1739 case GNU_AK_ALIGNED:
1740 /* __align__ may be used without an argument */
1741 if (attribute->have_arguments) {
1742 parse_gnu_attribute_const_arg(attribute);
1746 case GNU_AK_FORMAT_ARG:
1747 case GNU_AK_REGPARM:
1748 case GNU_AK_TRAP_EXIT:
1749 if (!attribute->have_arguments) {
1750 /* should have arguments */
1751 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1752 attribute->invalid = true;
1754 parse_gnu_attribute_const_arg(attribute);
1757 case GNU_AK_SECTION:
1758 case GNU_AK_SP_SWITCH:
1759 if (!attribute->have_arguments) {
1760 /* should have arguments */
1761 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1762 attribute->invalid = true;
1764 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1767 if (!attribute->have_arguments) {
1768 /* should have arguments */
1769 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1770 attribute->invalid = true;
1772 parse_gnu_attribute_format_args(attribute);
1774 case GNU_AK_WEAKREF:
1775 /* may have one string argument */
1776 if (attribute->have_arguments)
1777 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1779 case GNU_AK_NONNULL:
1780 if (attribute->have_arguments)
1781 parse_gnu_attribute_const_arg_list(attribute);
1783 case GNU_AK_TLS_MODEL:
1784 if (!attribute->have_arguments) {
1785 /* should have arguments */
1786 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1788 parse_gnu_attribute_tls_model_arg(attribute);
1790 case GNU_AK_VISIBILITY:
1791 if (!attribute->have_arguments) {
1792 /* should have arguments */
1793 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1795 parse_gnu_attribute_visibility_arg(attribute);
1798 if (!attribute->have_arguments) {
1799 /* should have arguments */
1800 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1802 parse_gnu_attribute_model_arg(attribute);
1806 if (!attribute->have_arguments) {
1807 /* should have arguments */
1808 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1810 parse_gnu_attribute_mode_arg(attribute);
1813 case GNU_AK_INTERRUPT:
1814 /* may have one string argument */
1815 if (attribute->have_arguments)
1816 parse_gnu_attribute_interrupt_arg(attribute);
1818 case GNU_AK_SENTINEL:
1819 /* may have one string argument */
1820 if (attribute->have_arguments)
1821 parse_gnu_attribute_const_arg(attribute);
1824 /* already handled */
1828 check_no_argument(attribute, name);
1831 if (attribute != NULL) {
1833 last->next = attribute;
1836 head = last = attribute;
1840 if (token.type != ',')
1854 * Parse GNU attributes.
1856 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1858 decl_modifiers_t modifiers = 0;
1861 switch (token.type) {
1862 case T___attribute__:
1863 modifiers |= parse_gnu_attribute(attributes);
1869 if (token.type != T_STRING_LITERAL) {
1870 parse_error_expected("while parsing assembler attribute",
1871 T_STRING_LITERAL, NULL);
1872 eat_until_matching_token('(');
1875 parse_string_literals();
1880 case T_cdecl: modifiers |= DM_CDECL; break;
1881 case T__fastcall: modifiers |= DM_FASTCALL; break;
1882 case T__stdcall: modifiers |= DM_STDCALL; break;
1885 /* TODO record modifier */
1887 warningf(HERE, "Ignoring declaration modifier %K", &token);
1891 default: return modifiers;
1898 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1900 static variable_t *determine_lhs_var(expression_t *const expr,
1901 variable_t *lhs_var)
1903 switch (expr->kind) {
1904 case EXPR_REFERENCE: {
1905 entity_t *const entity = expr->reference.entity;
1906 /* we should only find variables as lavlues... */
1907 if (entity->base.kind != ENTITY_VARIABLE)
1910 return &entity->variable;
1913 case EXPR_ARRAY_ACCESS: {
1914 expression_t *const ref = expr->array_access.array_ref;
1915 variable_t * var = NULL;
1916 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1917 var = determine_lhs_var(ref, lhs_var);
1920 mark_vars_read(expr->select.compound, lhs_var);
1922 mark_vars_read(expr->array_access.index, lhs_var);
1927 if (is_type_compound(skip_typeref(expr->base.type))) {
1928 return determine_lhs_var(expr->select.compound, lhs_var);
1930 mark_vars_read(expr->select.compound, lhs_var);
1935 case EXPR_UNARY_DEREFERENCE: {
1936 expression_t *const val = expr->unary.value;
1937 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1939 return determine_lhs_var(val->unary.value, lhs_var);
1941 mark_vars_read(val, NULL);
1947 mark_vars_read(expr, NULL);
1952 #define VAR_ANY ((variable_t*)-1)
1955 * Mark declarations, which are read. This is used to deted variables, which
1959 * x is not marked as "read", because it is only read to calculate its own new
1963 * x and y are not detected as "not read", because multiple variables are
1966 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1968 switch (expr->kind) {
1969 case EXPR_REFERENCE: {
1970 entity_t *const entity = expr->reference.entity;
1971 if (entity->kind != ENTITY_VARIABLE)
1974 variable_t *variable = &entity->variable;
1975 if (lhs_var != variable && lhs_var != VAR_ANY) {
1976 variable->read = true;
1982 // TODO respect pure/const
1983 mark_vars_read(expr->call.function, NULL);
1984 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1985 mark_vars_read(arg->expression, NULL);
1989 case EXPR_CONDITIONAL:
1990 // TODO lhs_decl should depend on whether true/false have an effect
1991 mark_vars_read(expr->conditional.condition, NULL);
1992 if (expr->conditional.true_expression != NULL)
1993 mark_vars_read(expr->conditional.true_expression, lhs_var);
1994 mark_vars_read(expr->conditional.false_expression, lhs_var);
1998 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2000 mark_vars_read(expr->select.compound, lhs_var);
2003 case EXPR_ARRAY_ACCESS: {
2004 expression_t *const ref = expr->array_access.array_ref;
2005 mark_vars_read(ref, lhs_var);
2006 lhs_var = determine_lhs_var(ref, lhs_var);
2007 mark_vars_read(expr->array_access.index, lhs_var);
2012 mark_vars_read(expr->va_arge.ap, lhs_var);
2015 case EXPR_UNARY_CAST:
2016 /* Special case: Use void cast to mark a variable as "read" */
2017 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2022 case EXPR_UNARY_THROW:
2023 if (expr->unary.value == NULL)
2026 case EXPR_UNARY_DEREFERENCE:
2027 case EXPR_UNARY_DELETE:
2028 case EXPR_UNARY_DELETE_ARRAY:
2029 if (lhs_var == VAR_ANY)
2033 case EXPR_UNARY_NEGATE:
2034 case EXPR_UNARY_PLUS:
2035 case EXPR_UNARY_BITWISE_NEGATE:
2036 case EXPR_UNARY_NOT:
2037 case EXPR_UNARY_TAKE_ADDRESS:
2038 case EXPR_UNARY_POSTFIX_INCREMENT:
2039 case EXPR_UNARY_POSTFIX_DECREMENT:
2040 case EXPR_UNARY_PREFIX_INCREMENT:
2041 case EXPR_UNARY_PREFIX_DECREMENT:
2042 case EXPR_UNARY_CAST_IMPLICIT:
2043 case EXPR_UNARY_ASSUME:
2045 mark_vars_read(expr->unary.value, lhs_var);
2048 case EXPR_BINARY_ADD:
2049 case EXPR_BINARY_SUB:
2050 case EXPR_BINARY_MUL:
2051 case EXPR_BINARY_DIV:
2052 case EXPR_BINARY_MOD:
2053 case EXPR_BINARY_EQUAL:
2054 case EXPR_BINARY_NOTEQUAL:
2055 case EXPR_BINARY_LESS:
2056 case EXPR_BINARY_LESSEQUAL:
2057 case EXPR_BINARY_GREATER:
2058 case EXPR_BINARY_GREATEREQUAL:
2059 case EXPR_BINARY_BITWISE_AND:
2060 case EXPR_BINARY_BITWISE_OR:
2061 case EXPR_BINARY_BITWISE_XOR:
2062 case EXPR_BINARY_LOGICAL_AND:
2063 case EXPR_BINARY_LOGICAL_OR:
2064 case EXPR_BINARY_SHIFTLEFT:
2065 case EXPR_BINARY_SHIFTRIGHT:
2066 case EXPR_BINARY_COMMA:
2067 case EXPR_BINARY_ISGREATER:
2068 case EXPR_BINARY_ISGREATEREQUAL:
2069 case EXPR_BINARY_ISLESS:
2070 case EXPR_BINARY_ISLESSEQUAL:
2071 case EXPR_BINARY_ISLESSGREATER:
2072 case EXPR_BINARY_ISUNORDERED:
2073 mark_vars_read(expr->binary.left, lhs_var);
2074 mark_vars_read(expr->binary.right, lhs_var);
2077 case EXPR_BINARY_ASSIGN:
2078 case EXPR_BINARY_MUL_ASSIGN:
2079 case EXPR_BINARY_DIV_ASSIGN:
2080 case EXPR_BINARY_MOD_ASSIGN:
2081 case EXPR_BINARY_ADD_ASSIGN:
2082 case EXPR_BINARY_SUB_ASSIGN:
2083 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2084 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2085 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2086 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2087 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2088 if (lhs_var == VAR_ANY)
2090 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2091 mark_vars_read(expr->binary.right, lhs_var);
2096 determine_lhs_var(expr->va_starte.ap, lhs_var);
2102 case EXPR_CHARACTER_CONSTANT:
2103 case EXPR_WIDE_CHARACTER_CONSTANT:
2104 case EXPR_STRING_LITERAL:
2105 case EXPR_WIDE_STRING_LITERAL:
2106 case EXPR_COMPOUND_LITERAL: // TODO init?
2108 case EXPR_CLASSIFY_TYPE:
2111 case EXPR_BUILTIN_SYMBOL:
2112 case EXPR_BUILTIN_CONSTANT_P:
2113 case EXPR_BUILTIN_PREFETCH:
2115 case EXPR_STATEMENT: // TODO
2116 case EXPR_LABEL_ADDRESS:
2117 case EXPR_BINARY_BUILTIN_EXPECT:
2118 case EXPR_REFERENCE_ENUM_VALUE:
2122 panic("unhandled expression");
2125 static designator_t *parse_designation(void)
2127 designator_t *result = NULL;
2128 designator_t *last = NULL;
2131 designator_t *designator;
2132 switch (token.type) {
2134 designator = allocate_ast_zero(sizeof(designator[0]));
2135 designator->source_position = token.source_position;
2137 add_anchor_token(']');
2138 designator->array_index = parse_constant_expression();
2139 rem_anchor_token(']');
2143 designator = allocate_ast_zero(sizeof(designator[0]));
2144 designator->source_position = token.source_position;
2146 if (token.type != T_IDENTIFIER) {
2147 parse_error_expected("while parsing designator",
2148 T_IDENTIFIER, NULL);
2151 designator->symbol = token.v.symbol;
2159 assert(designator != NULL);
2161 last->next = designator;
2163 result = designator;
2171 static initializer_t *initializer_from_string(array_type_t *type,
2172 const string_t *const string)
2174 /* TODO: check len vs. size of array type */
2177 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2178 initializer->string.string = *string;
2183 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2184 wide_string_t *const string)
2186 /* TODO: check len vs. size of array type */
2189 initializer_t *const initializer =
2190 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2191 initializer->wide_string.string = *string;
2197 * Build an initializer from a given expression.
2199 static initializer_t *initializer_from_expression(type_t *orig_type,
2200 expression_t *expression)
2202 /* TODO check that expression is a constant expression */
2204 /* § 6.7.8.14/15 char array may be initialized by string literals */
2205 type_t *type = skip_typeref(orig_type);
2206 type_t *expr_type_orig = expression->base.type;
2207 type_t *expr_type = skip_typeref(expr_type_orig);
2208 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2209 array_type_t *const array_type = &type->array;
2210 type_t *const element_type = skip_typeref(array_type->element_type);
2212 if (element_type->kind == TYPE_ATOMIC) {
2213 atomic_type_kind_t akind = element_type->atomic.akind;
2214 switch (expression->kind) {
2215 case EXPR_STRING_LITERAL:
2216 if (akind == ATOMIC_TYPE_CHAR
2217 || akind == ATOMIC_TYPE_SCHAR
2218 || akind == ATOMIC_TYPE_UCHAR) {
2219 return initializer_from_string(array_type,
2220 &expression->string.value);
2223 case EXPR_WIDE_STRING_LITERAL: {
2224 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2225 if (get_unqualified_type(element_type) == bare_wchar_type) {
2226 return initializer_from_wide_string(array_type,
2227 &expression->wide_string.value);
2237 assign_error_t error = semantic_assign(type, expression);
2238 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2240 report_assign_error(error, type, expression, "initializer",
2241 &expression->base.source_position);
2243 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2245 if (type->kind == TYPE_BITFIELD) {
2246 type = type->bitfield.base_type;
2249 result->value.value = create_implicit_cast(expression, type);
2255 * Checks if a given expression can be used as an constant initializer.
2257 static bool is_initializer_constant(const expression_t *expression)
2259 return is_constant_expression(expression)
2260 || is_address_constant(expression);
2264 * Parses an scalar initializer.
2266 * § 6.7.8.11; eat {} without warning
2268 static initializer_t *parse_scalar_initializer(type_t *type,
2269 bool must_be_constant)
2271 /* there might be extra {} hierarchies */
2273 if (token.type == '{') {
2275 warningf(HERE, "extra curly braces around scalar initializer");
2279 } while (token.type == '{');
2282 expression_t *expression = parse_assignment_expression();
2283 mark_vars_read(expression, NULL);
2284 if (must_be_constant && !is_initializer_constant(expression)) {
2285 errorf(&expression->base.source_position,
2286 "Initialisation expression '%E' is not constant\n",
2290 initializer_t *initializer = initializer_from_expression(type, expression);
2292 if (initializer == NULL) {
2293 errorf(&expression->base.source_position,
2294 "expression '%E' (type '%T') doesn't match expected type '%T'",
2295 expression, expression->base.type, type);
2300 bool additional_warning_displayed = false;
2301 while (braces > 0) {
2302 if (token.type == ',') {
2305 if (token.type != '}') {
2306 if (!additional_warning_displayed && warning.other) {
2307 warningf(HERE, "additional elements in scalar initializer");
2308 additional_warning_displayed = true;
2319 * An entry in the type path.
2321 typedef struct type_path_entry_t type_path_entry_t;
2322 struct type_path_entry_t {
2323 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2325 size_t index; /**< For array types: the current index. */
2326 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2331 * A type path expression a position inside compound or array types.
2333 typedef struct type_path_t type_path_t;
2334 struct type_path_t {
2335 type_path_entry_t *path; /**< An flexible array containing the current path. */
2336 type_t *top_type; /**< type of the element the path points */
2337 size_t max_index; /**< largest index in outermost array */
2341 * Prints a type path for debugging.
2343 static __attribute__((unused)) void debug_print_type_path(
2344 const type_path_t *path)
2346 size_t len = ARR_LEN(path->path);
2348 for (size_t i = 0; i < len; ++i) {
2349 const type_path_entry_t *entry = & path->path[i];
2351 type_t *type = skip_typeref(entry->type);
2352 if (is_type_compound(type)) {
2353 /* in gcc mode structs can have no members */
2354 if (entry->v.compound_entry == NULL) {
2358 fprintf(stderr, ".%s",
2359 entry->v.compound_entry->base.symbol->string);
2360 } else if (is_type_array(type)) {
2361 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2363 fprintf(stderr, "-INVALID-");
2366 if (path->top_type != NULL) {
2367 fprintf(stderr, " (");
2368 print_type(path->top_type);
2369 fprintf(stderr, ")");
2374 * Return the top type path entry, ie. in a path
2375 * (type).a.b returns the b.
2377 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2379 size_t len = ARR_LEN(path->path);
2381 return &path->path[len-1];
2385 * Enlarge the type path by an (empty) element.
2387 static type_path_entry_t *append_to_type_path(type_path_t *path)
2389 size_t len = ARR_LEN(path->path);
2390 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2392 type_path_entry_t *result = & path->path[len];
2393 memset(result, 0, sizeof(result[0]));
2398 * Descending into a sub-type. Enter the scope of the current top_type.
2400 static void descend_into_subtype(type_path_t *path)
2402 type_t *orig_top_type = path->top_type;
2403 type_t *top_type = skip_typeref(orig_top_type);
2405 type_path_entry_t *top = append_to_type_path(path);
2406 top->type = top_type;
2408 if (is_type_compound(top_type)) {
2409 compound_t *compound = top_type->compound.compound;
2410 entity_t *entry = compound->members.entities;
2412 if (entry != NULL) {
2413 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2414 top->v.compound_entry = &entry->declaration;
2415 path->top_type = entry->declaration.type;
2417 path->top_type = NULL;
2419 } else if (is_type_array(top_type)) {
2421 path->top_type = top_type->array.element_type;
2423 assert(!is_type_valid(top_type));
2428 * Pop an entry from the given type path, ie. returning from
2429 * (type).a.b to (type).a
2431 static void ascend_from_subtype(type_path_t *path)
2433 type_path_entry_t *top = get_type_path_top(path);
2435 path->top_type = top->type;
2437 size_t len = ARR_LEN(path->path);
2438 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2442 * Pop entries from the given type path until the given
2443 * path level is reached.
2445 static void ascend_to(type_path_t *path, size_t top_path_level)
2447 size_t len = ARR_LEN(path->path);
2449 while (len > top_path_level) {
2450 ascend_from_subtype(path);
2451 len = ARR_LEN(path->path);
2455 static bool walk_designator(type_path_t *path, const designator_t *designator,
2456 bool used_in_offsetof)
2458 for (; designator != NULL; designator = designator->next) {
2459 type_path_entry_t *top = get_type_path_top(path);
2460 type_t *orig_type = top->type;
2462 type_t *type = skip_typeref(orig_type);
2464 if (designator->symbol != NULL) {
2465 symbol_t *symbol = designator->symbol;
2466 if (!is_type_compound(type)) {
2467 if (is_type_valid(type)) {
2468 errorf(&designator->source_position,
2469 "'.%Y' designator used for non-compound type '%T'",
2473 top->type = type_error_type;
2474 top->v.compound_entry = NULL;
2475 orig_type = type_error_type;
2477 compound_t *compound = type->compound.compound;
2478 entity_t *iter = compound->members.entities;
2479 for (; iter != NULL; iter = iter->base.next) {
2480 if (iter->base.symbol == symbol) {
2485 errorf(&designator->source_position,
2486 "'%T' has no member named '%Y'", orig_type, symbol);
2489 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2490 if (used_in_offsetof) {
2491 type_t *real_type = skip_typeref(iter->declaration.type);
2492 if (real_type->kind == TYPE_BITFIELD) {
2493 errorf(&designator->source_position,
2494 "offsetof designator '%Y' may not specify bitfield",
2500 top->type = orig_type;
2501 top->v.compound_entry = &iter->declaration;
2502 orig_type = iter->declaration.type;
2505 expression_t *array_index = designator->array_index;
2506 assert(designator->array_index != NULL);
2508 if (!is_type_array(type)) {
2509 if (is_type_valid(type)) {
2510 errorf(&designator->source_position,
2511 "[%E] designator used for non-array type '%T'",
2512 array_index, orig_type);
2517 long index = fold_constant(array_index);
2518 if (!used_in_offsetof) {
2520 errorf(&designator->source_position,
2521 "array index [%E] must be positive", array_index);
2522 } else if (type->array.size_constant) {
2523 long array_size = type->array.size;
2524 if (index >= array_size) {
2525 errorf(&designator->source_position,
2526 "designator [%E] (%d) exceeds array size %d",
2527 array_index, index, array_size);
2532 top->type = orig_type;
2533 top->v.index = (size_t) index;
2534 orig_type = type->array.element_type;
2536 path->top_type = orig_type;
2538 if (designator->next != NULL) {
2539 descend_into_subtype(path);
2548 static void advance_current_object(type_path_t *path, size_t top_path_level)
2550 type_path_entry_t *top = get_type_path_top(path);
2552 type_t *type = skip_typeref(top->type);
2553 if (is_type_union(type)) {
2554 /* in unions only the first element is initialized */
2555 top->v.compound_entry = NULL;
2556 } else if (is_type_struct(type)) {
2557 declaration_t *entry = top->v.compound_entry;
2559 entity_t *next_entity = entry->base.next;
2560 if (next_entity != NULL) {
2561 assert(is_declaration(next_entity));
2562 entry = &next_entity->declaration;
2567 top->v.compound_entry = entry;
2568 if (entry != NULL) {
2569 path->top_type = entry->type;
2572 } else if (is_type_array(type)) {
2573 assert(is_type_array(type));
2577 if (!type->array.size_constant || top->v.index < type->array.size) {
2581 assert(!is_type_valid(type));
2585 /* we're past the last member of the current sub-aggregate, try if we
2586 * can ascend in the type hierarchy and continue with another subobject */
2587 size_t len = ARR_LEN(path->path);
2589 if (len > top_path_level) {
2590 ascend_from_subtype(path);
2591 advance_current_object(path, top_path_level);
2593 path->top_type = NULL;
2598 * skip until token is found.
2600 static void skip_until(int type)
2602 while (token.type != type) {
2603 if (token.type == T_EOF)
2610 * skip any {...} blocks until a closing bracket is reached.
2612 static void skip_initializers(void)
2614 if (token.type == '{')
2617 while (token.type != '}') {
2618 if (token.type == T_EOF)
2620 if (token.type == '{') {
2628 static initializer_t *create_empty_initializer(void)
2630 static initializer_t empty_initializer
2631 = { .list = { { INITIALIZER_LIST }, 0 } };
2632 return &empty_initializer;
2636 * Parse a part of an initialiser for a struct or union,
2638 static initializer_t *parse_sub_initializer(type_path_t *path,
2639 type_t *outer_type, size_t top_path_level,
2640 parse_initializer_env_t *env)
2642 if (token.type == '}') {
2643 /* empty initializer */
2644 return create_empty_initializer();
2647 type_t *orig_type = path->top_type;
2648 type_t *type = NULL;
2650 if (orig_type == NULL) {
2651 /* We are initializing an empty compound. */
2653 type = skip_typeref(orig_type);
2656 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2659 designator_t *designator = NULL;
2660 if (token.type == '.' || token.type == '[') {
2661 designator = parse_designation();
2662 goto finish_designator;
2663 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2664 /* GNU-style designator ("identifier: value") */
2665 designator = allocate_ast_zero(sizeof(designator[0]));
2666 designator->source_position = token.source_position;
2667 designator->symbol = token.v.symbol;
2672 /* reset path to toplevel, evaluate designator from there */
2673 ascend_to(path, top_path_level);
2674 if (!walk_designator(path, designator, false)) {
2675 /* can't continue after designation error */
2679 initializer_t *designator_initializer
2680 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2681 designator_initializer->designator.designator = designator;
2682 ARR_APP1(initializer_t*, initializers, designator_initializer);
2684 orig_type = path->top_type;
2685 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2690 if (token.type == '{') {
2691 if (type != NULL && is_type_scalar(type)) {
2692 sub = parse_scalar_initializer(type, env->must_be_constant);
2696 if (env->entity != NULL) {
2698 "extra brace group at end of initializer for '%Y'",
2699 env->entity->base.symbol);
2701 errorf(HERE, "extra brace group at end of initializer");
2704 descend_into_subtype(path);
2706 add_anchor_token('}');
2707 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2709 rem_anchor_token('}');
2712 ascend_from_subtype(path);
2716 goto error_parse_next;
2720 /* must be an expression */
2721 expression_t *expression = parse_assignment_expression();
2723 if (env->must_be_constant && !is_initializer_constant(expression)) {
2724 errorf(&expression->base.source_position,
2725 "Initialisation expression '%E' is not constant\n",
2730 /* we are already outside, ... */
2731 type_t *const outer_type_skip = skip_typeref(outer_type);
2732 if (is_type_compound(outer_type_skip) &&
2733 !outer_type_skip->compound.compound->complete) {
2734 goto error_parse_next;
2739 /* handle { "string" } special case */
2740 if ((expression->kind == EXPR_STRING_LITERAL
2741 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2742 && outer_type != NULL) {
2743 sub = initializer_from_expression(outer_type, expression);
2745 if (token.type == ',') {
2748 if (token.type != '}' && warning.other) {
2749 warningf(HERE, "excessive elements in initializer for type '%T'",
2752 /* TODO: eat , ... */
2757 /* descend into subtypes until expression matches type */
2759 orig_type = path->top_type;
2760 type = skip_typeref(orig_type);
2762 sub = initializer_from_expression(orig_type, expression);
2766 if (!is_type_valid(type)) {
2769 if (is_type_scalar(type)) {
2770 errorf(&expression->base.source_position,
2771 "expression '%E' doesn't match expected type '%T'",
2772 expression, orig_type);
2776 descend_into_subtype(path);
2780 /* update largest index of top array */
2781 const type_path_entry_t *first = &path->path[0];
2782 type_t *first_type = first->type;
2783 first_type = skip_typeref(first_type);
2784 if (is_type_array(first_type)) {
2785 size_t index = first->v.index;
2786 if (index > path->max_index)
2787 path->max_index = index;
2791 /* append to initializers list */
2792 ARR_APP1(initializer_t*, initializers, sub);
2795 if (warning.other) {
2796 if (env->entity != NULL) {
2797 warningf(HERE, "excess elements in struct initializer for '%Y'",
2798 env->entity->base.symbol);
2800 warningf(HERE, "excess elements in struct initializer");
2806 if (token.type == '}') {
2810 if (token.type == '}') {
2815 /* advance to the next declaration if we are not at the end */
2816 advance_current_object(path, top_path_level);
2817 orig_type = path->top_type;
2818 if (orig_type != NULL)
2819 type = skip_typeref(orig_type);
2825 size_t len = ARR_LEN(initializers);
2826 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2827 initializer_t *result = allocate_ast_zero(size);
2828 result->kind = INITIALIZER_LIST;
2829 result->list.len = len;
2830 memcpy(&result->list.initializers, initializers,
2831 len * sizeof(initializers[0]));
2833 DEL_ARR_F(initializers);
2834 ascend_to(path, top_path_level+1);
2839 skip_initializers();
2840 DEL_ARR_F(initializers);
2841 ascend_to(path, top_path_level+1);
2846 * Parses an initializer. Parsers either a compound literal
2847 * (env->declaration == NULL) or an initializer of a declaration.
2849 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2851 type_t *type = skip_typeref(env->type);
2852 initializer_t *result = NULL;
2855 if (is_type_scalar(type)) {
2856 result = parse_scalar_initializer(type, env->must_be_constant);
2857 } else if (token.type == '{') {
2861 memset(&path, 0, sizeof(path));
2862 path.top_type = env->type;
2863 path.path = NEW_ARR_F(type_path_entry_t, 0);
2865 descend_into_subtype(&path);
2867 add_anchor_token('}');
2868 result = parse_sub_initializer(&path, env->type, 1, env);
2869 rem_anchor_token('}');
2871 max_index = path.max_index;
2872 DEL_ARR_F(path.path);
2876 /* parse_scalar_initializer() also works in this case: we simply
2877 * have an expression without {} around it */
2878 result = parse_scalar_initializer(type, env->must_be_constant);
2881 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2882 * the array type size */
2883 if (is_type_array(type) && type->array.size_expression == NULL
2884 && result != NULL) {
2886 switch (result->kind) {
2887 case INITIALIZER_LIST:
2888 size = max_index + 1;
2891 case INITIALIZER_STRING:
2892 size = result->string.string.size;
2895 case INITIALIZER_WIDE_STRING:
2896 size = result->wide_string.string.size;
2899 case INITIALIZER_DESIGNATOR:
2900 case INITIALIZER_VALUE:
2901 /* can happen for parse errors */
2906 internal_errorf(HERE, "invalid initializer type");
2909 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2910 cnst->base.type = type_size_t;
2911 cnst->conste.v.int_value = size;
2913 type_t *new_type = duplicate_type(type);
2915 new_type->array.size_expression = cnst;
2916 new_type->array.size_constant = true;
2917 new_type->array.has_implicit_size = true;
2918 new_type->array.size = size;
2919 env->type = new_type;
2927 static void append_entity(scope_t *scope, entity_t *entity)
2929 if (scope->last_entity != NULL) {
2930 scope->last_entity->base.next = entity;
2932 scope->entities = entity;
2934 scope->last_entity = entity;
2938 static compound_t *parse_compound_type_specifier(bool is_struct)
2940 gnu_attribute_t *attributes = NULL;
2941 decl_modifiers_t modifiers = 0;
2948 symbol_t *symbol = NULL;
2949 compound_t *compound = NULL;
2951 if (token.type == T___attribute__) {
2952 modifiers |= parse_attributes(&attributes);
2955 if (token.type == T_IDENTIFIER) {
2956 symbol = token.v.symbol;
2959 namespace_tag_t const namespc =
2960 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2961 entity_t *entity = get_entity(symbol, namespc);
2962 if (entity != NULL) {
2963 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2964 compound = &entity->compound;
2965 if (compound->base.parent_scope != current_scope &&
2966 (token.type == '{' || token.type == ';')) {
2967 /* we're in an inner scope and have a definition. Override
2968 existing definition in outer scope */
2970 } else if (compound->complete && token.type == '{') {
2971 assert(symbol != NULL);
2972 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2973 is_struct ? "struct" : "union", symbol,
2974 &compound->base.source_position);
2975 /* clear members in the hope to avoid further errors */
2976 compound->members.entities = NULL;
2979 } else if (token.type != '{') {
2981 parse_error_expected("while parsing struct type specifier",
2982 T_IDENTIFIER, '{', NULL);
2984 parse_error_expected("while parsing union type specifier",
2985 T_IDENTIFIER, '{', NULL);
2991 if (compound == NULL) {
2992 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2993 entity_t *entity = allocate_entity_zero(kind);
2994 compound = &entity->compound;
2996 compound->base.namespc =
2997 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2998 compound->base.source_position = token.source_position;
2999 compound->base.symbol = symbol;
3000 compound->base.parent_scope = current_scope;
3001 if (symbol != NULL) {
3002 environment_push(entity);
3004 append_entity(current_scope, entity);
3007 if (token.type == '{') {
3008 parse_compound_type_entries(compound);
3009 modifiers |= parse_attributes(&attributes);
3011 if (symbol == NULL) {
3012 assert(anonymous_entity == NULL);
3013 anonymous_entity = (entity_t*)compound;
3017 compound->modifiers |= modifiers;
3021 static void parse_enum_entries(type_t *const enum_type)
3025 if (token.type == '}') {
3026 errorf(HERE, "empty enum not allowed");
3031 add_anchor_token('}');
3033 if (token.type != T_IDENTIFIER) {
3034 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3036 rem_anchor_token('}');
3040 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3041 entity->enum_value.enum_type = enum_type;
3042 entity->base.symbol = token.v.symbol;
3043 entity->base.source_position = token.source_position;
3046 if (token.type == '=') {
3048 expression_t *value = parse_constant_expression();
3050 value = create_implicit_cast(value, enum_type);
3051 entity->enum_value.value = value;
3056 record_entity(entity, false);
3058 if (token.type != ',')
3061 } while (token.type != '}');
3062 rem_anchor_token('}');
3070 static type_t *parse_enum_specifier(void)
3072 gnu_attribute_t *attributes = NULL;
3077 if (token.type == T_IDENTIFIER) {
3078 symbol = token.v.symbol;
3081 entity = get_entity(symbol, NAMESPACE_ENUM);
3082 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3083 } else if (token.type != '{') {
3084 parse_error_expected("while parsing enum type specifier",
3085 T_IDENTIFIER, '{', NULL);
3092 if (entity == NULL) {
3093 entity = allocate_entity_zero(ENTITY_ENUM);
3094 entity->base.namespc = NAMESPACE_ENUM;
3095 entity->base.source_position = token.source_position;
3096 entity->base.symbol = symbol;
3097 entity->base.parent_scope = current_scope;
3100 type_t *const type = allocate_type_zero(TYPE_ENUM);
3101 type->enumt.enume = &entity->enume;
3103 if (token.type == '{') {
3104 if (entity->enume.complete) {
3105 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3106 symbol, &entity->base.source_position);
3108 if (symbol != NULL) {
3109 environment_push(entity);
3111 append_entity(current_scope, entity);
3112 entity->enume.complete = true;
3114 parse_enum_entries(type);
3115 parse_attributes(&attributes);
3117 if (symbol == NULL) {
3118 assert(anonymous_entity == NULL);
3119 anonymous_entity = entity;
3121 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3122 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3130 * if a symbol is a typedef to another type, return true
3132 static bool is_typedef_symbol(symbol_t *symbol)
3134 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3135 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3138 static type_t *parse_typeof(void)
3145 add_anchor_token(')');
3147 expression_t *expression = NULL;
3149 bool old_type_prop = in_type_prop;
3150 bool old_gcc_extension = in_gcc_extension;
3151 in_type_prop = true;
3153 while (token.type == T___extension__) {
3154 /* This can be a prefix to a typename or an expression. */
3156 in_gcc_extension = true;
3158 switch (token.type) {
3160 if (is_typedef_symbol(token.v.symbol)) {
3161 type = parse_typename();
3163 expression = parse_expression();
3164 type = expression->base.type;
3169 type = parse_typename();
3173 expression = parse_expression();
3174 type = expression->base.type;
3177 in_type_prop = old_type_prop;
3178 in_gcc_extension = old_gcc_extension;
3180 rem_anchor_token(')');
3183 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3184 typeof_type->typeoft.expression = expression;
3185 typeof_type->typeoft.typeof_type = type;
3192 typedef enum specifiers_t {
3193 SPECIFIER_SIGNED = 1 << 0,
3194 SPECIFIER_UNSIGNED = 1 << 1,
3195 SPECIFIER_LONG = 1 << 2,
3196 SPECIFIER_INT = 1 << 3,
3197 SPECIFIER_DOUBLE = 1 << 4,
3198 SPECIFIER_CHAR = 1 << 5,
3199 SPECIFIER_SHORT = 1 << 6,
3200 SPECIFIER_LONG_LONG = 1 << 7,
3201 SPECIFIER_FLOAT = 1 << 8,
3202 SPECIFIER_BOOL = 1 << 9,
3203 SPECIFIER_VOID = 1 << 10,
3204 SPECIFIER_INT8 = 1 << 11,
3205 SPECIFIER_INT16 = 1 << 12,
3206 SPECIFIER_INT32 = 1 << 13,
3207 SPECIFIER_INT64 = 1 << 14,
3208 SPECIFIER_INT128 = 1 << 15,
3209 SPECIFIER_COMPLEX = 1 << 16,
3210 SPECIFIER_IMAGINARY = 1 << 17,
3213 static type_t *create_builtin_type(symbol_t *const symbol,
3214 type_t *const real_type)
3216 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3217 type->builtin.symbol = symbol;
3218 type->builtin.real_type = real_type;
3220 type_t *result = typehash_insert(type);
3221 if (type != result) {
3228 static type_t *get_typedef_type(symbol_t *symbol)
3230 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3231 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3234 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3235 type->typedeft.typedefe = &entity->typedefe;
3241 * check for the allowed MS alignment values.
3243 static bool check_alignment_value(long long intvalue)
3245 if (intvalue < 1 || intvalue > 8192) {
3246 errorf(HERE, "illegal alignment value");
3249 unsigned v = (unsigned)intvalue;
3250 for (unsigned i = 1; i <= 8192; i += i) {
3254 errorf(HERE, "alignment must be power of two");
3258 #define DET_MOD(name, tag) do { \
3259 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3260 *modifiers |= tag; \
3263 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3265 decl_modifiers_t *modifiers = &specifiers->modifiers;
3268 if (token.type == T_restrict) {
3270 DET_MOD(restrict, DM_RESTRICT);
3272 } else if (token.type != T_IDENTIFIER)
3274 symbol_t *symbol = token.v.symbol;
3275 if (symbol == sym_align) {
3278 if (token.type != T_INTEGER)
3280 if (check_alignment_value(token.v.intvalue)) {
3281 if (specifiers->alignment != 0 && warning.other)
3282 warningf(HERE, "align used more than once");
3283 specifiers->alignment = (unsigned char)token.v.intvalue;
3287 } else if (symbol == sym_allocate) {
3290 if (token.type != T_IDENTIFIER)
3292 (void)token.v.symbol;
3294 } else if (symbol == sym_dllimport) {
3296 DET_MOD(dllimport, DM_DLLIMPORT);
3297 } else if (symbol == sym_dllexport) {
3299 DET_MOD(dllexport, DM_DLLEXPORT);
3300 } else if (symbol == sym_thread) {
3302 DET_MOD(thread, DM_THREAD);
3303 } else if (symbol == sym_naked) {
3305 DET_MOD(naked, DM_NAKED);
3306 } else if (symbol == sym_noinline) {
3308 DET_MOD(noinline, DM_NOINLINE);
3309 } else if (symbol == sym_noreturn) {
3311 DET_MOD(noreturn, DM_NORETURN);
3312 } else if (symbol == sym_nothrow) {
3314 DET_MOD(nothrow, DM_NOTHROW);
3315 } else if (symbol == sym_novtable) {
3317 DET_MOD(novtable, DM_NOVTABLE);
3318 } else if (symbol == sym_property) {
3322 bool is_get = false;
3323 if (token.type != T_IDENTIFIER)
3325 if (token.v.symbol == sym_get) {
3327 } else if (token.v.symbol == sym_put) {
3329 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3334 if (token.type != T_IDENTIFIER)
3337 if (specifiers->get_property_sym != NULL) {
3338 errorf(HERE, "get property name already specified");
3340 specifiers->get_property_sym = token.v.symbol;
3343 if (specifiers->put_property_sym != NULL) {
3344 errorf(HERE, "put property name already specified");
3346 specifiers->put_property_sym = token.v.symbol;
3350 if (token.type == ',') {
3357 } else if (symbol == sym_selectany) {
3359 DET_MOD(selectany, DM_SELECTANY);
3360 } else if (symbol == sym_uuid) {
3363 if (token.type != T_STRING_LITERAL)
3367 } else if (symbol == sym_deprecated) {
3369 if (specifiers->deprecated != 0 && warning.other)
3370 warningf(HERE, "deprecated used more than once");
3371 specifiers->deprecated = true;
3372 if (token.type == '(') {
3374 if (token.type == T_STRING_LITERAL) {
3375 specifiers->deprecated_string = token.v.string.begin;
3378 errorf(HERE, "string literal expected");
3382 } else if (symbol == sym_noalias) {
3384 DET_MOD(noalias, DM_NOALIAS);
3387 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3389 if (token.type == '(')
3393 if (token.type == ',')
3400 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3402 entity_t *entity = allocate_entity_zero(kind);
3403 entity->base.source_position = *HERE;
3404 entity->base.symbol = symbol;
3405 if (is_declaration(entity)) {
3406 entity->declaration.type = type_error_type;
3407 entity->declaration.implicit = true;
3408 } else if (kind == ENTITY_TYPEDEF) {
3409 entity->typedefe.type = type_error_type;
3411 record_entity(entity, false);
3415 static void parse_microsoft_based(based_spec_t *based_spec)
3417 if (token.type != T_IDENTIFIER) {
3418 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3421 symbol_t *symbol = token.v.symbol;
3422 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3424 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3425 errorf(HERE, "'%Y' is not a variable name.", symbol);
3426 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3428 variable_t *variable = &entity->variable;
3430 if (based_spec->base_variable != NULL) {
3431 errorf(HERE, "__based type qualifier specified more than once");
3433 based_spec->source_position = token.source_position;
3434 based_spec->base_variable = variable;
3436 type_t *const type = variable->base.type;
3438 if (is_type_valid(type)) {
3439 if (! is_type_pointer(skip_typeref(type))) {
3440 errorf(HERE, "variable in __based modifier must have pointer type instead of %T", type);
3442 if (variable->base.base.parent_scope != file_scope) {
3443 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3451 * Finish the construction of a struct type by calculating
3452 * its size, offsets, alignment.
3454 static void finish_struct_type(compound_type_t *type)
3456 assert(type->compound != NULL);
3458 compound_t *compound = type->compound;
3459 if (!compound->complete)
3464 il_alignment_t alignment = 1;
3465 bool need_pad = false;
3467 entity_t *entry = compound->members.entities;
3468 for (; entry != NULL; entry = entry->base.next) {
3469 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3472 type_t *m_type = skip_typeref(entry->declaration.type);
3473 if (! is_type_valid(m_type)) {
3474 /* simply ignore errors here */
3477 il_alignment_t m_alignment = m_type->base.alignment;
3478 if (m_alignment > alignment)
3479 alignment = m_alignment;
3481 offset = (size + m_alignment - 1) & -m_alignment;
3485 entry->compound_member.offset = offset;
3486 size = offset + m_type->base.size;
3488 if (type->base.alignment != 0) {
3489 alignment = type->base.alignment;
3492 offset = (size + alignment - 1) & -alignment;
3496 if (warning.padded && need_pad) {
3497 warningf(&compound->base.source_position,
3498 "'%#T' needs padding", type, compound->base.symbol);
3500 if (warning.packed && !need_pad) {
3501 warningf(&compound->base.source_position,
3502 "superfluous packed attribute on '%#T'",
3503 type, compound->base.symbol);
3506 type->base.size = offset;
3507 type->base.alignment = alignment;
3511 * Finish the construction of an union type by calculating
3512 * its size and alignment.
3514 static void finish_union_type(compound_type_t *type)
3516 assert(type->compound != NULL);
3518 compound_t *compound = type->compound;
3519 if (! compound->complete)
3523 il_alignment_t alignment = 1;
3525 entity_t *entry = compound->members.entities;
3526 for (; entry != NULL; entry = entry->base.next) {
3527 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3530 type_t *m_type = skip_typeref(entry->declaration.type);
3531 if (! is_type_valid(m_type))
3534 entry->compound_member.offset = 0;
3535 if (m_type->base.size > size)
3536 size = m_type->base.size;
3537 if (m_type->base.alignment > alignment)
3538 alignment = m_type->base.alignment;
3540 if (type->base.alignment != 0) {
3541 alignment = type->base.alignment;
3543 size = (size + alignment - 1) & -alignment;
3544 type->base.size = size;
3545 type->base.alignment = alignment;
3548 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3550 type_t *type = NULL;
3551 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3552 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3553 unsigned type_specifiers = 0;
3554 bool newtype = false;
3555 bool saw_error = false;
3556 bool old_gcc_extension = in_gcc_extension;
3558 specifiers->source_position = token.source_position;
3561 specifiers->modifiers
3562 |= parse_attributes(&specifiers->gnu_attributes);
3563 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3564 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3566 switch (token.type) {
3569 #define MATCH_STORAGE_CLASS(token, class) \
3571 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3572 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3574 specifiers->storage_class = class; \
3578 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3579 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3580 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3581 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3582 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3587 add_anchor_token(')');
3588 parse_microsoft_extended_decl_modifier(specifiers);
3589 rem_anchor_token(')');
3594 switch (specifiers->storage_class) {
3595 case STORAGE_CLASS_NONE:
3596 specifiers->storage_class = STORAGE_CLASS_THREAD;
3599 case STORAGE_CLASS_EXTERN:
3600 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3603 case STORAGE_CLASS_STATIC:
3604 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3608 errorf(HERE, "multiple storage classes in declaration specifiers");
3614 /* type qualifiers */
3615 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3617 qualifiers |= qualifier; \
3621 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3622 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3623 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3624 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3625 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3626 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3627 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3628 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3630 case T___extension__:
3632 in_gcc_extension = true;
3635 /* type specifiers */
3636 #define MATCH_SPECIFIER(token, specifier, name) \
3638 if (type_specifiers & specifier) { \
3639 errorf(HERE, "multiple " name " type specifiers given"); \
3641 type_specifiers |= specifier; \
3646 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3647 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3648 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3649 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3650 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3651 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3652 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3653 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3654 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3655 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3656 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3657 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3658 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3659 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3660 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3661 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3662 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3664 case T__forceinline:
3665 /* only in microsoft mode */
3666 specifiers->modifiers |= DM_FORCEINLINE;
3671 specifiers->is_inline = true;
3675 if (type_specifiers & SPECIFIER_LONG_LONG) {
3676 errorf(HERE, "multiple type specifiers given");
3677 } else if (type_specifiers & SPECIFIER_LONG) {
3678 type_specifiers |= SPECIFIER_LONG_LONG;
3680 type_specifiers |= SPECIFIER_LONG;
3686 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3688 type->compound.compound = parse_compound_type_specifier(true);
3689 finish_struct_type(&type->compound);
3693 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3694 type->compound.compound = parse_compound_type_specifier(false);
3695 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3696 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3697 finish_union_type(&type->compound);
3701 type = parse_enum_specifier();
3704 type = parse_typeof();
3706 case T___builtin_va_list:
3707 type = duplicate_type(type_valist);
3711 case T_IDENTIFIER: {
3712 /* only parse identifier if we haven't found a type yet */
3713 if (type != NULL || type_specifiers != 0) {
3714 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3715 * declaration, so it doesn't generate errors about expecting '(' or
3717 switch (look_ahead(1)->type) {
3724 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3728 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3733 goto finish_specifiers;
3737 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3738 if (typedef_type == NULL) {
3739 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3740 * declaration, so it doesn't generate 'implicit int' followed by more
3741 * errors later on. */
3742 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3748 errorf(HERE, "%K does not name a type", &token);
3751 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3753 type = allocate_type_zero(TYPE_TYPEDEF);
3754 type->typedeft.typedefe = &entity->typedefe;
3758 if (la1_type == '&' || la1_type == '*')
3759 goto finish_specifiers;
3764 goto finish_specifiers;
3769 type = typedef_type;
3773 /* function specifier */
3775 goto finish_specifiers;
3780 in_gcc_extension = old_gcc_extension;
3782 if (type == NULL || (saw_error && type_specifiers != 0)) {
3783 atomic_type_kind_t atomic_type;
3785 /* match valid basic types */
3786 switch (type_specifiers) {
3787 case SPECIFIER_VOID:
3788 atomic_type = ATOMIC_TYPE_VOID;
3790 case SPECIFIER_CHAR:
3791 atomic_type = ATOMIC_TYPE_CHAR;
3793 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3794 atomic_type = ATOMIC_TYPE_SCHAR;
3796 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3797 atomic_type = ATOMIC_TYPE_UCHAR;
3799 case SPECIFIER_SHORT:
3800 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3801 case SPECIFIER_SHORT | SPECIFIER_INT:
3802 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3803 atomic_type = ATOMIC_TYPE_SHORT;
3805 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3806 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3807 atomic_type = ATOMIC_TYPE_USHORT;
3810 case SPECIFIER_SIGNED:
3811 case SPECIFIER_SIGNED | SPECIFIER_INT:
3812 atomic_type = ATOMIC_TYPE_INT;
3814 case SPECIFIER_UNSIGNED:
3815 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3816 atomic_type = ATOMIC_TYPE_UINT;
3818 case SPECIFIER_LONG:
3819 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3820 case SPECIFIER_LONG | SPECIFIER_INT:
3821 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3822 atomic_type = ATOMIC_TYPE_LONG;
3824 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3825 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3826 atomic_type = ATOMIC_TYPE_ULONG;
3829 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3830 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3831 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3832 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3834 atomic_type = ATOMIC_TYPE_LONGLONG;
3835 goto warn_about_long_long;
3837 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3838 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3840 atomic_type = ATOMIC_TYPE_ULONGLONG;
3841 warn_about_long_long:
3842 if (warning.long_long) {
3843 warningf(&specifiers->source_position,
3844 "ISO C90 does not support 'long long'");
3848 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3849 atomic_type = unsigned_int8_type_kind;
3852 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3853 atomic_type = unsigned_int16_type_kind;
3856 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3857 atomic_type = unsigned_int32_type_kind;
3860 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3861 atomic_type = unsigned_int64_type_kind;
3864 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3865 atomic_type = unsigned_int128_type_kind;
3868 case SPECIFIER_INT8:
3869 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3870 atomic_type = int8_type_kind;
3873 case SPECIFIER_INT16:
3874 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3875 atomic_type = int16_type_kind;
3878 case SPECIFIER_INT32:
3879 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3880 atomic_type = int32_type_kind;
3883 case SPECIFIER_INT64:
3884 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3885 atomic_type = int64_type_kind;
3888 case SPECIFIER_INT128:
3889 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3890 atomic_type = int128_type_kind;
3893 case SPECIFIER_FLOAT:
3894 atomic_type = ATOMIC_TYPE_FLOAT;
3896 case SPECIFIER_DOUBLE:
3897 atomic_type = ATOMIC_TYPE_DOUBLE;
3899 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3900 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3902 case SPECIFIER_BOOL:
3903 atomic_type = ATOMIC_TYPE_BOOL;
3905 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3906 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3907 atomic_type = ATOMIC_TYPE_FLOAT;
3909 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3910 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3911 atomic_type = ATOMIC_TYPE_DOUBLE;
3913 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3914 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3915 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3918 /* invalid specifier combination, give an error message */
3919 if (type_specifiers == 0) {
3923 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3924 if (!(c_mode & _CXX) && !strict_mode) {
3925 if (warning.implicit_int) {
3926 warningf(HERE, "no type specifiers in declaration, using 'int'");
3928 atomic_type = ATOMIC_TYPE_INT;
3931 errorf(HERE, "no type specifiers given in declaration");
3933 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3934 (type_specifiers & SPECIFIER_UNSIGNED)) {
3935 errorf(HERE, "signed and unsigned specifiers given");
3936 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3937 errorf(HERE, "only integer types can be signed or unsigned");
3939 errorf(HERE, "multiple datatypes in declaration");
3944 if (type_specifiers & SPECIFIER_COMPLEX) {
3945 type = allocate_type_zero(TYPE_COMPLEX);
3946 type->complex.akind = atomic_type;
3947 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3948 type = allocate_type_zero(TYPE_IMAGINARY);
3949 type->imaginary.akind = atomic_type;
3951 type = allocate_type_zero(TYPE_ATOMIC);
3952 type->atomic.akind = atomic_type;
3955 } else if (type_specifiers != 0) {
3956 errorf(HERE, "multiple datatypes in declaration");
3959 /* FIXME: check type qualifiers here */
3961 type->base.qualifiers = qualifiers;
3962 type->base.modifiers = modifiers;
3964 type_t *result = typehash_insert(type);
3965 if (newtype && result != type) {
3969 specifiers->type = result;
3973 specifiers->type = type_error_type;
3977 static type_qualifiers_t parse_type_qualifiers(void)
3979 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3982 switch (token.type) {
3983 /* type qualifiers */
3984 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3985 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3986 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3987 /* microsoft extended type modifiers */
3988 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3989 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3990 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3991 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3992 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4001 * Parses an K&R identifier list
4003 static void parse_identifier_list(scope_t *scope)
4006 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4007 entity->base.source_position = token.source_position;
4008 entity->base.namespc = NAMESPACE_NORMAL;
4009 entity->base.symbol = token.v.symbol;
4010 /* a K&R parameter has no type, yet */
4013 append_entity(scope, entity);
4015 if (token.type != ',') {
4019 } while (token.type == T_IDENTIFIER);
4022 static type_t *automatic_type_conversion(type_t *orig_type);
4024 static void semantic_parameter(declaration_t *declaration)
4026 /* TODO: improve error messages */
4027 source_position_t const* const pos = &declaration->base.source_position;
4030 switch (declaration->declared_storage_class) {
4031 /* Allowed storage classes */
4032 case STORAGE_CLASS_NONE:
4033 case STORAGE_CLASS_REGISTER:
4037 errorf(pos, "parameter may only have none or register storage class");
4041 type_t *const orig_type = declaration->type;
4042 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4043 * sugar. Turn it into a pointer.
4044 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4045 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4047 type_t *const type = automatic_type_conversion(orig_type);
4048 declaration->type = type;
4050 if (is_type_incomplete(skip_typeref(type))) {
4051 errorf(pos, "parameter '%#T' is of incomplete type",
4052 orig_type, declaration->base.symbol);
4056 static entity_t *parse_parameter(void)
4058 declaration_specifiers_t specifiers;
4059 memset(&specifiers, 0, sizeof(specifiers));
4061 parse_declaration_specifiers(&specifiers);
4063 entity_t *entity = parse_declarator(&specifiers, true, false);
4064 anonymous_entity = NULL;
4069 * Parses function type parameters (and optionally creates variable_t entities
4070 * for them in a scope)
4072 static void parse_parameters(function_type_t *type, scope_t *scope)
4075 add_anchor_token(')');
4076 int saved_comma_state = save_and_reset_anchor_state(',');
4078 if (token.type == T_IDENTIFIER &&
4079 !is_typedef_symbol(token.v.symbol)) {
4080 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4081 if (la1_type == ',' || la1_type == ')') {
4082 type->kr_style_parameters = true;
4083 parse_identifier_list(scope);
4084 goto parameters_finished;
4088 if (token.type == ')') {
4089 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4090 if (!(c_mode & _CXX))
4091 type->unspecified_parameters = true;
4092 goto parameters_finished;
4095 function_parameter_t *parameter;
4096 function_parameter_t *last_parameter = NULL;
4099 switch (token.type) {
4102 type->variadic = true;
4103 goto parameters_finished;
4106 case T___extension__:
4109 entity_t *entity = parse_parameter();
4110 if (entity->kind == ENTITY_TYPEDEF) {
4111 errorf(&entity->base.source_position,
4112 "typedef not allowed as function parameter");
4115 assert(is_declaration(entity));
4117 /* func(void) is not a parameter */
4118 if (last_parameter == NULL
4119 && token.type == ')'
4120 && entity->base.symbol == NULL
4121 && skip_typeref(entity->declaration.type) == type_void) {
4122 goto parameters_finished;
4124 semantic_parameter(&entity->declaration);
4126 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4127 memset(parameter, 0, sizeof(parameter[0]));
4128 parameter->type = entity->declaration.type;
4130 if (scope != NULL) {
4131 append_entity(scope, entity);
4134 if (last_parameter != NULL) {
4135 last_parameter->next = parameter;
4137 type->parameters = parameter;
4139 last_parameter = parameter;
4144 goto parameters_finished;
4146 if (token.type != ',') {
4147 goto parameters_finished;
4153 parameters_finished:
4154 rem_anchor_token(')');
4158 restore_anchor_state(',', saved_comma_state);
4161 typedef enum construct_type_kind_t {
4164 CONSTRUCT_REFERENCE,
4167 } construct_type_kind_t;
4169 typedef struct construct_type_t construct_type_t;
4170 struct construct_type_t {
4171 construct_type_kind_t kind;
4172 construct_type_t *next;
4175 typedef struct parsed_pointer_t parsed_pointer_t;
4176 struct parsed_pointer_t {
4177 construct_type_t construct_type;
4178 type_qualifiers_t type_qualifiers;
4179 variable_t *base_variable; /**< MS __based extension. */
4182 typedef struct parsed_reference_t parsed_reference_t;
4183 struct parsed_reference_t {
4184 construct_type_t construct_type;
4187 typedef struct construct_function_type_t construct_function_type_t;
4188 struct construct_function_type_t {
4189 construct_type_t construct_type;
4190 type_t *function_type;
4193 typedef struct parsed_array_t parsed_array_t;
4194 struct parsed_array_t {
4195 construct_type_t construct_type;
4196 type_qualifiers_t type_qualifiers;
4202 typedef struct construct_base_type_t construct_base_type_t;
4203 struct construct_base_type_t {
4204 construct_type_t construct_type;
4208 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4212 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4213 memset(pointer, 0, sizeof(pointer[0]));
4214 pointer->construct_type.kind = CONSTRUCT_POINTER;
4215 pointer->type_qualifiers = parse_type_qualifiers();
4216 pointer->base_variable = base_variable;
4218 return &pointer->construct_type;
4221 static construct_type_t *parse_reference_declarator(void)
4225 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4226 memset(reference, 0, sizeof(reference[0]));
4227 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4229 return (construct_type_t*)reference;
4232 static construct_type_t *parse_array_declarator(void)
4235 add_anchor_token(']');
4237 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4238 memset(array, 0, sizeof(array[0]));
4239 array->construct_type.kind = CONSTRUCT_ARRAY;
4241 if (token.type == T_static) {
4242 array->is_static = true;
4246 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4247 if (type_qualifiers != 0) {
4248 if (token.type == T_static) {
4249 array->is_static = true;
4253 array->type_qualifiers = type_qualifiers;
4255 if (token.type == '*' && look_ahead(1)->type == ']') {
4256 array->is_variable = true;
4258 } else if (token.type != ']') {
4259 array->size = parse_assignment_expression();
4262 rem_anchor_token(']');
4266 return &array->construct_type;
4269 static construct_type_t *parse_function_declarator(scope_t *scope,
4270 decl_modifiers_t modifiers)
4272 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4273 function_type_t *ftype = &type->function;
4275 ftype->linkage = current_linkage;
4277 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4278 case DM_NONE: break;
4279 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4280 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4281 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4282 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4285 errorf(HERE, "multiple calling conventions in declaration");
4289 parse_parameters(ftype, scope);
4291 construct_function_type_t *construct_function_type =
4292 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4293 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4294 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4295 construct_function_type->function_type = type;
4297 return &construct_function_type->construct_type;
4300 typedef struct parse_declarator_env_t {
4301 decl_modifiers_t modifiers;
4303 source_position_t source_position;
4305 } parse_declarator_env_t;
4307 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4308 bool may_be_abstract)
4310 /* construct a single linked list of construct_type_t's which describe
4311 * how to construct the final declarator type */
4312 construct_type_t *first = NULL;
4313 construct_type_t *last = NULL;
4314 gnu_attribute_t *attributes = NULL;
4316 decl_modifiers_t modifiers = parse_attributes(&attributes);
4318 /* MS __based extension */
4319 based_spec_t base_spec;
4320 base_spec.base_variable = NULL;
4323 construct_type_t *type;
4324 switch (token.type) {
4326 if (!(c_mode & _CXX))
4327 errorf(HERE, "references are only available for C++");
4328 if (base_spec.base_variable != NULL)
4329 warningf(&base_spec.source_position,
4330 "__based does not precede a pointer operator, ignored");
4331 type = parse_reference_declarator();
4333 base_spec.base_variable = NULL;
4337 type = parse_pointer_declarator(base_spec.base_variable);
4339 base_spec.base_variable = NULL;
4345 add_anchor_token(')');
4346 parse_microsoft_based(&base_spec);
4347 rem_anchor_token(')');
4352 goto ptr_operator_end;
4363 /* TODO: find out if this is correct */
4364 modifiers |= parse_attributes(&attributes);
4367 if (base_spec.base_variable != NULL)
4368 warningf(&base_spec.source_position,
4369 "__based does not precede a pointer operator, ignored");
4372 modifiers |= env->modifiers;
4373 env->modifiers = modifiers;
4376 construct_type_t *inner_types = NULL;
4378 switch (token.type) {
4381 errorf(HERE, "no identifier expected in typename");
4383 env->symbol = token.v.symbol;
4384 env->source_position = token.source_position;
4390 add_anchor_token(')');
4391 inner_types = parse_inner_declarator(env, may_be_abstract);
4392 if (inner_types != NULL) {
4393 /* All later declarators only modify the return type */
4396 rem_anchor_token(')');
4400 if (may_be_abstract)
4402 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4407 construct_type_t *p = last;
4410 construct_type_t *type;
4411 switch (token.type) {
4413 scope_t *scope = NULL;
4415 scope = &env->parameters;
4417 type = parse_function_declarator(scope, modifiers);
4421 type = parse_array_declarator();
4424 goto declarator_finished;
4427 /* insert in the middle of the list (behind p) */
4429 type->next = p->next;
4440 declarator_finished:
4441 /* append inner_types at the end of the list, we don't to set last anymore
4442 * as it's not needed anymore */
4444 assert(first == NULL);
4445 first = inner_types;
4447 last->next = inner_types;
4455 static void parse_declaration_attributes(entity_t *entity)
4457 gnu_attribute_t *attributes = NULL;
4458 decl_modifiers_t modifiers = parse_attributes(&attributes);
4464 if (entity->kind == ENTITY_TYPEDEF) {
4465 modifiers |= entity->typedefe.modifiers;
4466 type = entity->typedefe.type;
4468 assert(is_declaration(entity));
4469 modifiers |= entity->declaration.modifiers;
4470 type = entity->declaration.type;
4475 /* handle these strange/stupid mode attributes */
4476 gnu_attribute_t *attribute = attributes;
4477 for ( ; attribute != NULL; attribute = attribute->next) {
4478 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4481 atomic_type_kind_t akind = attribute->u.akind;
4482 if (!is_type_signed(type)) {
4484 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4485 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4486 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4487 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4489 panic("invalid akind in mode attribute");
4493 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4494 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4495 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4496 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4498 panic("invalid akind in mode attribute");
4502 type = make_atomic_type(akind, type->base.qualifiers);
4505 type_modifiers_t type_modifiers = type->base.modifiers;
4506 if (modifiers & DM_TRANSPARENT_UNION)
4507 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4509 if (type->base.modifiers != type_modifiers) {
4510 type_t *copy = duplicate_type(type);
4511 copy->base.modifiers = type_modifiers;
4513 type = typehash_insert(copy);
4515 obstack_free(type_obst, copy);
4519 if (entity->kind == ENTITY_TYPEDEF) {
4520 entity->typedefe.type = type;
4521 entity->typedefe.modifiers = modifiers;
4523 entity->declaration.type = type;
4524 entity->declaration.modifiers = modifiers;
4528 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4530 construct_type_t *iter = construct_list;
4531 for (; iter != NULL; iter = iter->next) {
4532 switch (iter->kind) {
4533 case CONSTRUCT_INVALID:
4534 internal_errorf(HERE, "invalid type construction found");
4535 case CONSTRUCT_FUNCTION: {
4536 construct_function_type_t *construct_function_type
4537 = (construct_function_type_t*) iter;
4539 type_t *function_type = construct_function_type->function_type;
4541 function_type->function.return_type = type;
4543 type_t *skipped_return_type = skip_typeref(type);
4545 if (is_type_function(skipped_return_type)) {
4546 errorf(HERE, "function returning function is not allowed");
4547 } else if (is_type_array(skipped_return_type)) {
4548 errorf(HERE, "function returning array is not allowed");
4550 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4552 "type qualifiers in return type of function type are meaningless");
4556 type = function_type;
4560 case CONSTRUCT_POINTER: {
4561 if (is_type_reference(skip_typeref(type)))
4562 errorf(HERE, "cannot declare a pointer to reference");
4564 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4565 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4569 case CONSTRUCT_REFERENCE:
4570 if (is_type_reference(skip_typeref(type)))
4571 errorf(HERE, "cannot declare a reference to reference");
4573 type = make_reference_type(type);
4576 case CONSTRUCT_ARRAY: {
4577 if (is_type_reference(skip_typeref(type)))
4578 errorf(HERE, "cannot declare an array of references");
4580 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4581 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4583 expression_t *size_expression = parsed_array->size;
4584 if (size_expression != NULL) {
4586 = create_implicit_cast(size_expression, type_size_t);
4589 array_type->base.qualifiers = parsed_array->type_qualifiers;
4590 array_type->array.element_type = type;
4591 array_type->array.is_static = parsed_array->is_static;
4592 array_type->array.is_variable = parsed_array->is_variable;
4593 array_type->array.size_expression = size_expression;
4595 if (size_expression != NULL) {
4596 if (is_constant_expression(size_expression)) {
4597 array_type->array.size_constant = true;
4598 array_type->array.size
4599 = fold_constant(size_expression);
4601 array_type->array.is_vla = true;
4605 type_t *skipped_type = skip_typeref(type);
4607 if (is_type_incomplete(skipped_type)) {
4608 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4609 } else if (is_type_function(skipped_type)) {
4610 errorf(HERE, "array of functions is not allowed");
4617 type_t *hashed_type = typehash_insert(type);
4618 if (hashed_type != type) {
4619 /* the function type was constructed earlier freeing it here will
4620 * destroy other types... */
4621 if (iter->kind != CONSTRUCT_FUNCTION) {
4631 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4632 bool may_be_abstract,
4633 bool create_compound_member)
4635 parse_declarator_env_t env;
4636 memset(&env, 0, sizeof(env));
4637 env.modifiers = specifiers->modifiers;
4639 construct_type_t *construct_type
4640 = parse_inner_declarator(&env, may_be_abstract);
4641 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4643 if (construct_type != NULL) {
4644 obstack_free(&temp_obst, construct_type);
4648 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4649 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4650 entity->base.symbol = env.symbol;
4651 entity->base.source_position = env.source_position;
4652 entity->typedefe.type = type;
4654 if (anonymous_entity != NULL) {
4655 if (is_type_compound(type)) {
4656 assert(anonymous_entity->compound.alias == NULL);
4657 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4658 anonymous_entity->kind == ENTITY_UNION);
4659 anonymous_entity->compound.alias = entity;
4660 anonymous_entity = NULL;
4661 } else if (is_type_enum(type)) {
4662 assert(anonymous_entity->enume.alias == NULL);
4663 assert(anonymous_entity->kind == ENTITY_ENUM);
4664 anonymous_entity->enume.alias = entity;
4665 anonymous_entity = NULL;
4669 if (create_compound_member) {
4670 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4671 } else if (is_type_function(skip_typeref(type))) {
4672 entity = allocate_entity_zero(ENTITY_FUNCTION);
4674 entity->function.is_inline = specifiers->is_inline;
4675 entity->function.parameters = env.parameters;
4677 entity = allocate_entity_zero(ENTITY_VARIABLE);
4679 entity->variable.get_property_sym = specifiers->get_property_sym;
4680 entity->variable.put_property_sym = specifiers->put_property_sym;
4681 if (specifiers->alignment != 0) {
4682 /* TODO: add checks here */
4683 entity->variable.alignment = specifiers->alignment;
4686 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4687 warningf(&env.source_position,
4688 "variable '%Y' declared 'inline'\n", env.symbol);
4692 entity->base.source_position = env.source_position;
4693 entity->base.symbol = env.symbol;
4694 entity->base.namespc = NAMESPACE_NORMAL;
4695 entity->declaration.type = type;
4696 entity->declaration.modifiers = env.modifiers;
4697 entity->declaration.deprecated_string = specifiers->deprecated_string;
4699 storage_class_t storage_class = specifiers->storage_class;
4700 entity->declaration.declared_storage_class = storage_class;
4702 if (storage_class == STORAGE_CLASS_NONE
4703 && current_scope != file_scope) {
4704 storage_class = STORAGE_CLASS_AUTO;
4706 entity->declaration.storage_class = storage_class;
4709 parse_declaration_attributes(entity);
4714 static type_t *parse_abstract_declarator(type_t *base_type)
4716 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4718 type_t *result = construct_declarator_type(construct_type, base_type);
4719 if (construct_type != NULL) {
4720 obstack_free(&temp_obst, construct_type);
4727 * Check if the declaration of main is suspicious. main should be a
4728 * function with external linkage, returning int, taking either zero
4729 * arguments, two, or three arguments of appropriate types, ie.
4731 * int main([ int argc, char **argv [, char **env ] ]).
4733 * @param decl the declaration to check
4734 * @param type the function type of the declaration
4736 static void check_type_of_main(const entity_t *entity)
4738 const source_position_t *pos = &entity->base.source_position;
4739 if (entity->kind != ENTITY_FUNCTION) {
4740 warningf(pos, "'main' is not a function");
4744 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4745 warningf(pos, "'main' is normally a non-static function");
4748 type_t *type = skip_typeref(entity->declaration.type);
4749 assert(is_type_function(type));
4751 function_type_t *func_type = &type->function;
4752 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4753 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4754 func_type->return_type);
4756 const function_parameter_t *parm = func_type->parameters;
4758 type_t *const first_type = parm->type;
4759 if (!types_compatible(skip_typeref(first_type), type_int)) {
4761 "first argument of 'main' should be 'int', but is '%T'",
4766 type_t *const second_type = parm->type;
4767 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4768 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4772 type_t *const third_type = parm->type;
4773 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4774 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4778 goto warn_arg_count;
4782 warningf(pos, "'main' takes only zero, two or three arguments");
4788 * Check if a symbol is the equal to "main".
4790 static bool is_sym_main(const symbol_t *const sym)
4792 return strcmp(sym->string, "main") == 0;
4795 static const char *get_entity_kind_name(entity_kind_t kind)
4797 switch ((entity_kind_tag_t) kind) {
4798 case ENTITY_FUNCTION: return "function";
4799 case ENTITY_VARIABLE: return "variable";
4800 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4801 case ENTITY_STRUCT: return "struct";
4802 case ENTITY_UNION: return "union";
4803 case ENTITY_ENUM: return "enum";
4804 case ENTITY_ENUM_VALUE: return "enum value";
4805 case ENTITY_LABEL: return "label";
4806 case ENTITY_LOCAL_LABEL: return "local label";
4807 case ENTITY_TYPEDEF: return "typedef";
4808 case ENTITY_NAMESPACE: return "namespace";
4809 case ENTITY_INVALID: break;
4812 panic("Invalid entity kind encountered in get_entity_kind_name");
4815 static void error_redefined_as_different_kind(const source_position_t *pos,
4816 const entity_t *old, entity_kind_t new_kind)
4818 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4819 get_entity_kind_name(old->kind), old->base.symbol,
4820 get_entity_kind_name(new_kind), &old->base.source_position);
4824 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4825 * for various problems that occur for multiple definitions
4827 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4829 const symbol_t *const symbol = entity->base.symbol;
4830 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4831 const source_position_t *pos = &entity->base.source_position;
4833 assert(symbol != NULL);
4834 entity_t *previous_entity = get_entity(symbol, namespc);
4835 /* pushing the same entity twice will break the stack structure */
4836 assert(previous_entity != entity);
4838 if (entity->kind == ENTITY_FUNCTION) {
4839 type_t *const orig_type = entity->declaration.type;
4840 type_t *const type = skip_typeref(orig_type);
4842 assert(is_type_function(type));
4843 if (type->function.unspecified_parameters &&
4844 warning.strict_prototypes &&
4845 previous_entity == NULL) {
4846 warningf(pos, "function declaration '%#T' is not a prototype",
4850 if (warning.main && current_scope == file_scope
4851 && is_sym_main(symbol)) {
4852 check_type_of_main(entity);
4856 if (is_declaration(entity)) {
4857 if (warning.nested_externs
4858 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4859 && current_scope != file_scope) {
4860 warningf(pos, "nested extern declaration of '%#T'",
4861 entity->declaration.type, symbol);
4865 if (previous_entity != NULL
4866 && previous_entity->base.parent_scope == ¤t_function->parameters
4867 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4869 assert(previous_entity->kind == ENTITY_VARIABLE);
4871 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4872 entity->declaration.type, symbol,
4873 previous_entity->declaration.type, symbol,
4874 &previous_entity->base.source_position);
4878 if (previous_entity != NULL
4879 && previous_entity->base.parent_scope == current_scope) {
4881 if (previous_entity->kind != entity->kind) {
4882 error_redefined_as_different_kind(pos, previous_entity,
4886 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4888 "redeclaration of enum entry '%Y' (declared %P)",
4889 symbol, &previous_entity->base.source_position);
4892 if (previous_entity->kind == ENTITY_TYPEDEF) {
4893 /* TODO: C++ allows this for exactly the same type */
4895 "redefinition of typedef '%Y' (declared %P)",
4896 symbol, &previous_entity->base.source_position);
4900 /* at this point we should have only VARIABLES or FUNCTIONS */
4901 assert(is_declaration(previous_entity) && is_declaration(entity));
4903 /* can happen for K&R style declarations */
4904 if (previous_entity->kind == ENTITY_VARIABLE
4905 && previous_entity->declaration.type == NULL
4906 && entity->kind == ENTITY_VARIABLE) {
4907 previous_entity->declaration.type = entity->declaration.type;
4908 previous_entity->declaration.storage_class
4909 = entity->declaration.storage_class;
4910 previous_entity->declaration.declared_storage_class
4911 = entity->declaration.declared_storage_class;
4912 previous_entity->declaration.modifiers
4913 = entity->declaration.modifiers;
4914 previous_entity->declaration.deprecated_string
4915 = entity->declaration.deprecated_string;
4917 assert(entity->declaration.type != NULL);
4919 declaration_t *const previous_declaration
4920 = &previous_entity->declaration;
4921 declaration_t *const declaration = &entity->declaration;
4922 type_t *const orig_type = entity->declaration.type;
4923 type_t *const type = skip_typeref(orig_type);
4925 type_t *prev_type = skip_typeref(previous_declaration->type);
4927 if (!types_compatible(type, prev_type)) {
4929 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4930 orig_type, symbol, previous_declaration->type, symbol,
4931 &previous_entity->base.source_position);
4933 unsigned old_storage_class = previous_declaration->storage_class;
4934 if (warning.redundant_decls && is_definition
4935 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4936 && !(previous_declaration->modifiers & DM_USED)
4937 && !previous_declaration->used) {
4938 warningf(&previous_entity->base.source_position,
4939 "unnecessary static forward declaration for '%#T'",
4940 previous_declaration->type, symbol);
4943 unsigned new_storage_class = declaration->storage_class;
4944 if (is_type_incomplete(prev_type)) {
4945 previous_declaration->type = type;
4949 /* pretend no storage class means extern for function
4950 * declarations (except if the previous declaration is neither
4951 * none nor extern) */
4952 if (entity->kind == ENTITY_FUNCTION) {
4953 if (prev_type->function.unspecified_parameters) {
4954 previous_declaration->type = type;
4958 switch (old_storage_class) {
4959 case STORAGE_CLASS_NONE:
4960 old_storage_class = STORAGE_CLASS_EXTERN;
4963 case STORAGE_CLASS_EXTERN:
4964 if (is_definition) {
4965 if (warning.missing_prototypes &&
4966 prev_type->function.unspecified_parameters &&
4967 !is_sym_main(symbol)) {
4968 warningf(pos, "no previous prototype for '%#T'",
4971 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4972 new_storage_class = STORAGE_CLASS_EXTERN;
4981 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4982 new_storage_class == STORAGE_CLASS_EXTERN) {
4983 warn_redundant_declaration:
4984 if (!is_definition &&
4985 warning.redundant_decls &&
4986 is_type_valid(prev_type) &&
4987 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4989 "redundant declaration for '%Y' (declared %P)",
4990 symbol, &previous_entity->base.source_position);
4992 } else if (current_function == NULL) {
4993 if (old_storage_class != STORAGE_CLASS_STATIC &&
4994 new_storage_class == STORAGE_CLASS_STATIC) {
4996 "static declaration of '%Y' follows non-static declaration (declared %P)",
4997 symbol, &previous_entity->base.source_position);
4998 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4999 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5000 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5002 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5004 goto error_redeclaration;
5005 goto warn_redundant_declaration;
5007 } else if (is_type_valid(prev_type)) {
5008 if (old_storage_class == new_storage_class) {
5009 error_redeclaration:
5010 errorf(pos, "redeclaration of '%Y' (declared %P)",
5011 symbol, &previous_entity->base.source_position);
5014 "redeclaration of '%Y' with different linkage (declared %P)",
5015 symbol, &previous_entity->base.source_position);
5020 previous_declaration->modifiers |= declaration->modifiers;
5021 if (entity->kind == ENTITY_FUNCTION) {
5022 previous_entity->function.is_inline |= entity->function.is_inline;
5024 return previous_entity;
5027 if (entity->kind == ENTITY_FUNCTION) {
5028 if (is_definition &&
5029 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5030 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5031 warningf(pos, "no previous prototype for '%#T'",
5032 entity->declaration.type, symbol);
5033 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5034 warningf(pos, "no previous declaration for '%#T'",
5035 entity->declaration.type, symbol);
5038 } else if (warning.missing_declarations
5039 && entity->kind == ENTITY_VARIABLE
5040 && current_scope == file_scope) {
5041 declaration_t *declaration = &entity->declaration;
5042 if (declaration->storage_class == STORAGE_CLASS_NONE ||
5043 declaration->storage_class == STORAGE_CLASS_THREAD) {
5044 warningf(pos, "no previous declaration for '%#T'",
5045 declaration->type, symbol);
5050 assert(entity->base.parent_scope == NULL);
5051 assert(current_scope != NULL);
5053 entity->base.parent_scope = current_scope;
5054 entity->base.namespc = NAMESPACE_NORMAL;
5055 environment_push(entity);
5056 append_entity(current_scope, entity);
5061 static void parser_error_multiple_definition(entity_t *entity,
5062 const source_position_t *source_position)
5064 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5065 entity->base.symbol, &entity->base.source_position);
5068 static bool is_declaration_specifier(const token_t *token,
5069 bool only_specifiers_qualifiers)
5071 switch (token->type) {
5076 return is_typedef_symbol(token->v.symbol);
5078 case T___extension__:
5080 return !only_specifiers_qualifiers;
5087 static void parse_init_declarator_rest(entity_t *entity)
5089 assert(is_declaration(entity));
5090 declaration_t *const declaration = &entity->declaration;
5094 type_t *orig_type = declaration->type;
5095 type_t *type = skip_typeref(orig_type);
5097 if (entity->kind == ENTITY_VARIABLE
5098 && entity->variable.initializer != NULL) {
5099 parser_error_multiple_definition(entity, HERE);
5102 bool must_be_constant = false;
5103 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5104 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5105 entity->base.parent_scope == file_scope) {
5106 must_be_constant = true;
5109 if (is_type_function(type)) {
5110 errorf(&entity->base.source_position,
5111 "function '%#T' is initialized like a variable",
5112 orig_type, entity->base.symbol);
5113 orig_type = type_error_type;
5116 parse_initializer_env_t env;
5117 env.type = orig_type;
5118 env.must_be_constant = must_be_constant;
5119 env.entity = entity;
5120 current_init_decl = entity;
5122 initializer_t *initializer = parse_initializer(&env);
5123 current_init_decl = NULL;
5125 if (entity->kind == ENTITY_VARIABLE) {
5126 /* § 6.7.5 (22) array initializers for arrays with unknown size
5127 * determine the array type size */
5128 declaration->type = env.type;
5129 entity->variable.initializer = initializer;
5133 /* parse rest of a declaration without any declarator */
5134 static void parse_anonymous_declaration_rest(
5135 const declaration_specifiers_t *specifiers)
5138 anonymous_entity = NULL;
5140 if (warning.other) {
5141 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5142 warningf(&specifiers->source_position,
5143 "useless storage class in empty declaration");
5146 type_t *type = specifiers->type;
5147 switch (type->kind) {
5148 case TYPE_COMPOUND_STRUCT:
5149 case TYPE_COMPOUND_UNION: {
5150 if (type->compound.compound->base.symbol == NULL) {
5151 warningf(&specifiers->source_position,
5152 "unnamed struct/union that defines no instances");
5161 warningf(&specifiers->source_position, "empty declaration");
5167 static void check_variable_type_complete(entity_t *ent)
5169 if (ent->kind != ENTITY_VARIABLE)
5172 declaration_t *decl = &ent->declaration;
5173 if (decl->storage_class == STORAGE_CLASS_EXTERN)
5176 type_t *type = decl->type;
5177 if (!is_type_incomplete(skip_typeref(type)))
5180 errorf(&ent->base.source_position,
5181 "variable '%#T' is of incomplete type", type, ent->base.symbol);
5185 static void parse_declaration_rest(entity_t *ndeclaration,
5186 const declaration_specifiers_t *specifiers,
5187 parsed_declaration_func finished_declaration)
5189 add_anchor_token(';');
5190 add_anchor_token(',');
5192 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5194 if (token.type == '=') {
5195 parse_init_declarator_rest(entity);
5198 check_variable_type_complete(entity);
5200 if (token.type != ',')
5204 add_anchor_token('=');
5205 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5206 rem_anchor_token('=');
5211 anonymous_entity = NULL;
5212 rem_anchor_token(';');
5213 rem_anchor_token(',');
5216 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5218 symbol_t *symbol = entity->base.symbol;
5219 if (symbol == NULL) {
5220 errorf(HERE, "anonymous declaration not valid as function parameter");
5224 assert(entity->base.namespc == NAMESPACE_NORMAL);
5225 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5226 if (previous_entity == NULL
5227 || previous_entity->base.parent_scope != current_scope) {
5228 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5233 if (is_definition) {
5234 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5237 return record_entity(entity, false);
5240 static void parse_declaration(parsed_declaration_func finished_declaration)
5242 declaration_specifiers_t specifiers;
5243 memset(&specifiers, 0, sizeof(specifiers));
5245 add_anchor_token(';');
5246 parse_declaration_specifiers(&specifiers);
5247 rem_anchor_token(';');
5249 if (token.type == ';') {
5250 parse_anonymous_declaration_rest(&specifiers);
5252 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5253 parse_declaration_rest(entity, &specifiers, finished_declaration);
5257 static type_t *get_default_promoted_type(type_t *orig_type)
5259 type_t *result = orig_type;
5261 type_t *type = skip_typeref(orig_type);
5262 if (is_type_integer(type)) {
5263 result = promote_integer(type);
5264 } else if (type == type_float) {
5265 result = type_double;
5271 static void parse_kr_declaration_list(entity_t *entity)
5273 if (entity->kind != ENTITY_FUNCTION)
5276 type_t *type = skip_typeref(entity->declaration.type);
5277 assert(is_type_function(type));
5278 if (!type->function.kr_style_parameters)
5282 add_anchor_token('{');
5284 /* push function parameters */
5285 size_t const top = environment_top();
5286 scope_push(&entity->function.parameters);
5288 entity_t *parameter = entity->function.parameters.entities;
5289 for ( ; parameter != NULL; parameter = parameter->base.next) {
5290 assert(parameter->base.parent_scope == NULL);
5291 parameter->base.parent_scope = current_scope;
5292 environment_push(parameter);
5295 /* parse declaration list */
5296 while (is_declaration_specifier(&token, false)) {
5297 parse_declaration(finished_kr_declaration);
5300 /* pop function parameters */
5301 assert(current_scope == &entity->function.parameters);
5303 environment_pop_to(top);
5305 /* update function type */
5306 type_t *new_type = duplicate_type(type);
5308 function_parameter_t *parameters = NULL;
5309 function_parameter_t *last_parameter = NULL;
5311 entity_t *parameter_declaration = entity->function.parameters.entities;
5312 for (; parameter_declaration != NULL;
5313 parameter_declaration = parameter_declaration->base.next) {
5314 type_t *parameter_type = parameter_declaration->declaration.type;
5315 if (parameter_type == NULL) {
5317 errorf(HERE, "no type specified for function parameter '%Y'",
5318 parameter_declaration->base.symbol);
5320 if (warning.implicit_int) {
5321 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5322 parameter_declaration->base.symbol);
5324 parameter_type = type_int;
5325 parameter_declaration->declaration.type = parameter_type;
5329 semantic_parameter(¶meter_declaration->declaration);
5330 parameter_type = parameter_declaration->declaration.type;
5333 * we need the default promoted types for the function type
5335 parameter_type = get_default_promoted_type(parameter_type);
5337 function_parameter_t *function_parameter
5338 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5339 memset(function_parameter, 0, sizeof(function_parameter[0]));
5341 function_parameter->type = parameter_type;
5342 if (last_parameter != NULL) {
5343 last_parameter->next = function_parameter;
5345 parameters = function_parameter;
5347 last_parameter = function_parameter;
5350 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5352 new_type->function.parameters = parameters;
5353 new_type->function.unspecified_parameters = true;
5355 type = typehash_insert(new_type);
5356 if (type != new_type) {
5357 obstack_free(type_obst, new_type);
5360 entity->declaration.type = type;
5362 rem_anchor_token('{');
5365 static bool first_err = true;
5368 * When called with first_err set, prints the name of the current function,
5371 static void print_in_function(void)
5375 diagnosticf("%s: In function '%Y':\n",
5376 current_function->base.base.source_position.input_name,
5377 current_function->base.base.symbol);
5382 * Check if all labels are defined in the current function.
5383 * Check if all labels are used in the current function.
5385 static void check_labels(void)
5387 for (const goto_statement_t *goto_statement = goto_first;
5388 goto_statement != NULL;
5389 goto_statement = goto_statement->next) {
5390 /* skip computed gotos */
5391 if (goto_statement->expression != NULL)
5394 label_t *label = goto_statement->label;
5397 if (label->base.source_position.input_name == NULL) {
5398 print_in_function();
5399 errorf(&goto_statement->base.source_position,
5400 "label '%Y' used but not defined", label->base.symbol);
5404 if (warning.unused_label) {
5405 for (const label_statement_t *label_statement = label_first;
5406 label_statement != NULL;
5407 label_statement = label_statement->next) {
5408 label_t *label = label_statement->label;
5410 if (! label->used) {
5411 print_in_function();
5412 warningf(&label_statement->base.source_position,
5413 "label '%Y' defined but not used", label->base.symbol);
5419 static void warn_unused_decl(entity_t *entity, entity_t *end,
5420 char const *const what)
5422 for (; entity != NULL; entity = entity->base.next) {
5423 if (!is_declaration(entity))
5426 declaration_t *declaration = &entity->declaration;
5427 if (declaration->implicit)
5430 if (!declaration->used) {
5431 print_in_function();
5432 warningf(&entity->base.source_position, "%s '%Y' is unused",
5433 what, entity->base.symbol);
5434 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5435 print_in_function();
5436 warningf(&entity->base.source_position, "%s '%Y' is never read",
5437 what, entity->base.symbol);
5445 static void check_unused_variables(statement_t *const stmt, void *const env)
5449 switch (stmt->kind) {
5450 case STATEMENT_DECLARATION: {
5451 declaration_statement_t const *const decls = &stmt->declaration;
5452 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5458 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5467 * Check declarations of current_function for unused entities.
5469 static void check_declarations(void)
5471 if (warning.unused_parameter) {
5472 const scope_t *scope = ¤t_function->parameters;
5474 /* do not issue unused warnings for main */
5475 if (!is_sym_main(current_function->base.base.symbol)) {
5476 warn_unused_decl(scope->entities, NULL, "parameter");
5479 if (warning.unused_variable) {
5480 walk_statements(current_function->statement, check_unused_variables,
5485 static int determine_truth(expression_t const* const cond)
5488 !is_constant_expression(cond) ? 0 :
5489 fold_constant(cond) != 0 ? 1 :
5493 static bool expression_returns(expression_t const *const expr)
5495 switch (expr->kind) {
5497 expression_t const *const func = expr->call.function;
5498 if (func->kind == EXPR_REFERENCE) {
5499 entity_t *entity = func->reference.entity;
5500 if (entity->kind == ENTITY_FUNCTION
5501 && entity->declaration.modifiers & DM_NORETURN)
5505 if (!expression_returns(func))
5508 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5509 if (!expression_returns(arg->expression))
5516 case EXPR_REFERENCE:
5517 case EXPR_REFERENCE_ENUM_VALUE:
5519 case EXPR_CHARACTER_CONSTANT:
5520 case EXPR_WIDE_CHARACTER_CONSTANT:
5521 case EXPR_STRING_LITERAL:
5522 case EXPR_WIDE_STRING_LITERAL:
5523 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5524 case EXPR_LABEL_ADDRESS:
5525 case EXPR_CLASSIFY_TYPE:
5526 case EXPR_SIZEOF: // TODO handle obscure VLA case
5529 case EXPR_BUILTIN_SYMBOL:
5530 case EXPR_BUILTIN_CONSTANT_P:
5531 case EXPR_BUILTIN_PREFETCH:
5534 case EXPR_STATEMENT: // TODO implement
5537 case EXPR_CONDITIONAL:
5538 // TODO handle constant expression
5540 expression_returns(expr->conditional.condition) && (
5541 expression_returns(expr->conditional.true_expression) ||
5542 expression_returns(expr->conditional.false_expression)
5546 return expression_returns(expr->select.compound);
5548 case EXPR_ARRAY_ACCESS:
5550 expression_returns(expr->array_access.array_ref) &&
5551 expression_returns(expr->array_access.index);
5554 return expression_returns(expr->va_starte.ap);
5557 return expression_returns(expr->va_arge.ap);
5559 EXPR_UNARY_CASES_MANDATORY
5560 return expression_returns(expr->unary.value);
5562 case EXPR_UNARY_THROW:
5566 // TODO handle constant lhs of && and ||
5568 expression_returns(expr->binary.left) &&
5569 expression_returns(expr->binary.right);
5575 panic("unhandled expression");
5578 static bool noreturn_candidate;
5580 static void check_reachable(statement_t *const stmt)
5582 if (stmt->base.reachable)
5584 if (stmt->kind != STATEMENT_DO_WHILE)
5585 stmt->base.reachable = true;
5587 statement_t *last = stmt;
5589 switch (stmt->kind) {
5590 case STATEMENT_INVALID:
5591 case STATEMENT_EMPTY:
5592 case STATEMENT_DECLARATION:
5593 case STATEMENT_LOCAL_LABEL:
5595 next = stmt->base.next;
5598 case STATEMENT_COMPOUND:
5599 next = stmt->compound.statements;
5602 case STATEMENT_RETURN:
5603 noreturn_candidate = false;
5606 case STATEMENT_IF: {
5607 if_statement_t const* const ifs = &stmt->ifs;
5608 int const val = determine_truth(ifs->condition);
5611 check_reachable(ifs->true_statement);
5616 if (ifs->false_statement != NULL) {
5617 check_reachable(ifs->false_statement);
5621 next = stmt->base.next;
5625 case STATEMENT_SWITCH: {
5626 switch_statement_t const *const switchs = &stmt->switchs;
5627 expression_t const *const expr = switchs->expression;
5629 if (is_constant_expression(expr)) {
5630 long const val = fold_constant(expr);
5631 case_label_statement_t * defaults = NULL;
5632 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5633 if (i->expression == NULL) {
5638 if (i->first_case <= val && val <= i->last_case) {
5639 check_reachable((statement_t*)i);
5644 if (defaults != NULL) {
5645 check_reachable((statement_t*)defaults);
5649 bool has_default = false;
5650 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5651 if (i->expression == NULL)
5654 check_reachable((statement_t*)i);
5661 next = stmt->base.next;
5665 case STATEMENT_EXPRESSION: {
5666 /* Check for noreturn function call */
5667 expression_t const *const expr = stmt->expression.expression;
5668 if (!expression_returns(expr))
5671 next = stmt->base.next;
5675 case STATEMENT_CONTINUE: {
5676 statement_t *parent = stmt;
5678 parent = parent->base.parent;
5679 if (parent == NULL) /* continue not within loop */
5683 switch (parent->kind) {
5684 case STATEMENT_WHILE: goto continue_while;
5685 case STATEMENT_DO_WHILE: goto continue_do_while;
5686 case STATEMENT_FOR: goto continue_for;
5693 case STATEMENT_BREAK: {
5694 statement_t *parent = stmt;
5696 parent = parent->base.parent;
5697 if (parent == NULL) /* break not within loop/switch */
5700 switch (parent->kind) {
5701 case STATEMENT_SWITCH:
5702 case STATEMENT_WHILE:
5703 case STATEMENT_DO_WHILE:
5706 next = parent->base.next;
5707 goto found_break_parent;
5716 case STATEMENT_GOTO:
5717 if (stmt->gotos.expression) {
5718 statement_t *parent = stmt->base.parent;
5719 if (parent == NULL) /* top level goto */
5723 next = stmt->gotos.label->statement;
5724 if (next == NULL) /* missing label */
5729 case STATEMENT_LABEL:
5730 next = stmt->label.statement;
5733 case STATEMENT_CASE_LABEL:
5734 next = stmt->case_label.statement;
5737 case STATEMENT_WHILE: {
5738 while_statement_t const *const whiles = &stmt->whiles;
5739 int const val = determine_truth(whiles->condition);
5742 check_reachable(whiles->body);
5747 next = stmt->base.next;
5751 case STATEMENT_DO_WHILE:
5752 next = stmt->do_while.body;
5755 case STATEMENT_FOR: {
5756 for_statement_t *const fors = &stmt->fors;
5758 if (fors->condition_reachable)
5760 fors->condition_reachable = true;
5762 expression_t const *const cond = fors->condition;
5764 cond == NULL ? 1 : determine_truth(cond);
5767 check_reachable(fors->body);
5772 next = stmt->base.next;
5776 case STATEMENT_MS_TRY: {
5777 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5778 check_reachable(ms_try->try_statement);
5779 next = ms_try->final_statement;
5783 case STATEMENT_LEAVE: {
5784 statement_t *parent = stmt;
5786 parent = parent->base.parent;
5787 if (parent == NULL) /* __leave not within __try */
5790 if (parent->kind == STATEMENT_MS_TRY) {
5792 next = parent->ms_try.final_statement;
5800 while (next == NULL) {
5801 next = last->base.parent;
5803 noreturn_candidate = false;
5805 type_t *const type = current_function->base.type;
5806 assert(is_type_function(type));
5807 type_t *const ret = skip_typeref(type->function.return_type);
5808 if (warning.return_type &&
5809 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5810 is_type_valid(ret) &&
5811 !is_sym_main(current_function->base.base.symbol)) {
5812 warningf(&stmt->base.source_position,
5813 "control reaches end of non-void function");
5818 switch (next->kind) {
5819 case STATEMENT_INVALID:
5820 case STATEMENT_EMPTY:
5821 case STATEMENT_DECLARATION:
5822 case STATEMENT_LOCAL_LABEL:
5823 case STATEMENT_EXPRESSION:
5825 case STATEMENT_RETURN:
5826 case STATEMENT_CONTINUE:
5827 case STATEMENT_BREAK:
5828 case STATEMENT_GOTO:
5829 case STATEMENT_LEAVE:
5830 panic("invalid control flow in function");
5832 case STATEMENT_COMPOUND:
5834 case STATEMENT_SWITCH:
5835 case STATEMENT_LABEL:
5836 case STATEMENT_CASE_LABEL:
5838 next = next->base.next;
5841 case STATEMENT_WHILE: {
5843 if (next->base.reachable)
5845 next->base.reachable = true;
5847 while_statement_t const *const whiles = &next->whiles;
5848 int const val = determine_truth(whiles->condition);
5851 check_reachable(whiles->body);
5857 next = next->base.next;
5861 case STATEMENT_DO_WHILE: {
5863 if (next->base.reachable)
5865 next->base.reachable = true;
5867 do_while_statement_t const *const dw = &next->do_while;
5868 int const val = determine_truth(dw->condition);
5871 check_reachable(dw->body);
5877 next = next->base.next;
5881 case STATEMENT_FOR: {
5883 for_statement_t *const fors = &next->fors;
5885 fors->step_reachable = true;
5887 if (fors->condition_reachable)
5889 fors->condition_reachable = true;
5891 expression_t const *const cond = fors->condition;
5893 cond == NULL ? 1 : determine_truth(cond);
5896 check_reachable(fors->body);
5902 next = next->base.next;
5906 case STATEMENT_MS_TRY:
5908 next = next->ms_try.final_statement;
5913 check_reachable(next);
5916 static void check_unreachable(statement_t* const stmt, void *const env)
5920 switch (stmt->kind) {
5921 case STATEMENT_DO_WHILE:
5922 if (!stmt->base.reachable) {
5923 expression_t const *const cond = stmt->do_while.condition;
5924 if (determine_truth(cond) >= 0) {
5925 warningf(&cond->base.source_position,
5926 "condition of do-while-loop is unreachable");
5931 case STATEMENT_FOR: {
5932 for_statement_t const* const fors = &stmt->fors;
5934 // if init and step are unreachable, cond is unreachable, too
5935 if (!stmt->base.reachable && !fors->step_reachable) {
5936 warningf(&stmt->base.source_position, "statement is unreachable");
5938 if (!stmt->base.reachable && fors->initialisation != NULL) {
5939 warningf(&fors->initialisation->base.source_position,
5940 "initialisation of for-statement is unreachable");
5943 if (!fors->condition_reachable && fors->condition != NULL) {
5944 warningf(&fors->condition->base.source_position,
5945 "condition of for-statement is unreachable");
5948 if (!fors->step_reachable && fors->step != NULL) {
5949 warningf(&fors->step->base.source_position,
5950 "step of for-statement is unreachable");
5956 case STATEMENT_COMPOUND:
5957 if (stmt->compound.statements != NULL)
5962 if (!stmt->base.reachable)
5963 warningf(&stmt->base.source_position, "statement is unreachable");
5968 static void parse_external_declaration(void)
5970 /* function-definitions and declarations both start with declaration
5972 declaration_specifiers_t specifiers;
5973 memset(&specifiers, 0, sizeof(specifiers));
5975 add_anchor_token(';');
5976 parse_declaration_specifiers(&specifiers);
5977 rem_anchor_token(';');
5979 /* must be a declaration */
5980 if (token.type == ';') {
5981 parse_anonymous_declaration_rest(&specifiers);
5985 add_anchor_token(',');
5986 add_anchor_token('=');
5987 add_anchor_token(';');
5988 add_anchor_token('{');
5990 /* declarator is common to both function-definitions and declarations */
5991 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5993 rem_anchor_token('{');
5994 rem_anchor_token(';');
5995 rem_anchor_token('=');
5996 rem_anchor_token(',');
5998 /* must be a declaration */
5999 switch (token.type) {
6003 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6007 /* must be a function definition */
6008 parse_kr_declaration_list(ndeclaration);
6010 if (token.type != '{') {
6011 parse_error_expected("while parsing function definition", '{', NULL);
6012 eat_until_matching_token(';');
6016 assert(is_declaration(ndeclaration));
6017 type_t *type = skip_typeref(ndeclaration->declaration.type);
6019 if (!is_type_function(type)) {
6020 if (is_type_valid(type)) {
6021 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6022 type, ndeclaration->base.symbol);
6028 if (warning.aggregate_return &&
6029 is_type_compound(skip_typeref(type->function.return_type))) {
6030 warningf(HERE, "function '%Y' returns an aggregate",
6031 ndeclaration->base.symbol);
6033 if (warning.traditional && !type->function.unspecified_parameters) {
6034 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6035 ndeclaration->base.symbol);
6037 if (warning.old_style_definition && type->function.unspecified_parameters) {
6038 warningf(HERE, "old-style function definition '%Y'",
6039 ndeclaration->base.symbol);
6042 /* § 6.7.5.3 (14) a function definition with () means no
6043 * parameters (and not unspecified parameters) */
6044 if (type->function.unspecified_parameters
6045 && type->function.parameters == NULL
6046 && !type->function.kr_style_parameters) {
6047 type_t *duplicate = duplicate_type(type);
6048 duplicate->function.unspecified_parameters = false;
6050 type = typehash_insert(duplicate);
6051 if (type != duplicate) {
6052 obstack_free(type_obst, duplicate);
6054 ndeclaration->declaration.type = type;
6057 entity_t *const entity = record_entity(ndeclaration, true);
6058 assert(entity->kind == ENTITY_FUNCTION);
6059 assert(ndeclaration->kind == ENTITY_FUNCTION);
6061 function_t *function = &entity->function;
6062 if (ndeclaration != entity) {
6063 function->parameters = ndeclaration->function.parameters;
6065 assert(is_declaration(entity));
6066 type = skip_typeref(entity->declaration.type);
6068 /* push function parameters and switch scope */
6069 size_t const top = environment_top();
6070 scope_push(&function->parameters);
6072 entity_t *parameter = function->parameters.entities;
6073 for (; parameter != NULL; parameter = parameter->base.next) {
6074 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6075 parameter->base.parent_scope = current_scope;
6077 assert(parameter->base.parent_scope == NULL
6078 || parameter->base.parent_scope == current_scope);
6079 parameter->base.parent_scope = current_scope;
6080 if (parameter->base.symbol == NULL) {
6081 errorf(¶meter->base.source_position, "parameter name omitted");
6084 environment_push(parameter);
6087 if (function->statement != NULL) {
6088 parser_error_multiple_definition(entity, HERE);
6091 /* parse function body */
6092 int label_stack_top = label_top();
6093 function_t *old_current_function = current_function;
6094 current_function = function;
6095 current_parent = NULL;
6098 goto_anchor = &goto_first;
6100 label_anchor = &label_first;
6102 statement_t *const body = parse_compound_statement(false);
6103 function->statement = body;
6106 check_declarations();
6107 if (warning.return_type ||
6108 warning.unreachable_code ||
6109 (warning.missing_noreturn
6110 && !(function->base.modifiers & DM_NORETURN))) {
6111 noreturn_candidate = true;
6112 check_reachable(body);
6113 if (warning.unreachable_code)
6114 walk_statements(body, check_unreachable, NULL);
6115 if (warning.missing_noreturn &&
6116 noreturn_candidate &&
6117 !(function->base.modifiers & DM_NORETURN)) {
6118 warningf(&body->base.source_position,
6119 "function '%#T' is candidate for attribute 'noreturn'",
6120 type, entity->base.symbol);
6124 assert(current_parent == NULL);
6125 assert(current_function == function);
6126 current_function = old_current_function;
6127 label_pop_to(label_stack_top);
6130 assert(current_scope == &function->parameters);
6132 environment_pop_to(top);
6135 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6136 source_position_t *source_position,
6137 const symbol_t *symbol)
6139 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6141 type->bitfield.base_type = base_type;
6142 type->bitfield.size_expression = size;
6145 type_t *skipped_type = skip_typeref(base_type);
6146 if (!is_type_integer(skipped_type)) {
6147 errorf(HERE, "bitfield base type '%T' is not an integer type",
6151 bit_size = skipped_type->base.size * 8;
6154 if (is_constant_expression(size)) {
6155 long v = fold_constant(size);
6158 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6159 } else if (v == 0) {
6160 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6161 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6162 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6164 type->bitfield.bit_size = v;
6171 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6173 entity_t *iter = compound->members.entities;
6174 for (; iter != NULL; iter = iter->base.next) {
6175 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6178 if (iter->base.symbol == symbol) {
6180 } else if (iter->base.symbol == NULL) {
6181 type_t *type = skip_typeref(iter->declaration.type);
6182 if (is_type_compound(type)) {
6184 = find_compound_entry(type->compound.compound, symbol);
6195 static void parse_compound_declarators(compound_t *compound,
6196 const declaration_specifiers_t *specifiers)
6201 if (token.type == ':') {
6202 source_position_t source_position = *HERE;
6205 type_t *base_type = specifiers->type;
6206 expression_t *size = parse_constant_expression();
6208 type_t *type = make_bitfield_type(base_type, size,
6209 &source_position, sym_anonymous);
6211 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6212 entity->base.namespc = NAMESPACE_NORMAL;
6213 entity->base.source_position = source_position;
6214 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6215 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6216 entity->declaration.modifiers = specifiers->modifiers;
6217 entity->declaration.type = type;
6219 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6220 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6222 if (token.type == ':') {
6223 source_position_t source_position = *HERE;
6225 expression_t *size = parse_constant_expression();
6227 type_t *type = entity->declaration.type;
6228 type_t *bitfield_type = make_bitfield_type(type, size,
6229 &source_position, entity->base.symbol);
6230 entity->declaration.type = bitfield_type;
6234 /* make sure we don't define a symbol multiple times */
6235 symbol_t *symbol = entity->base.symbol;
6236 if (symbol != NULL) {
6237 entity_t *prev = find_compound_entry(compound, symbol);
6240 errorf(&entity->base.source_position,
6241 "multiple declarations of symbol '%Y' (declared %P)",
6242 symbol, &prev->base.source_position);
6246 append_entity(&compound->members, entity);
6248 type_t *orig_type = entity->declaration.type;
6249 type_t *type = skip_typeref(orig_type);
6250 if (is_type_function(type)) {
6251 errorf(&entity->base.source_position,
6252 "compound member '%Y' must not have function type '%T'",
6253 entity->base.symbol, orig_type);
6254 } else if (is_type_incomplete(type)) {
6255 /* §6.7.2.1:16 flexible array member */
6256 if (is_type_array(type) &&
6257 token.type == ';' &&
6258 look_ahead(1)->type == '}') {
6259 compound->has_flexible_member = true;
6261 errorf(&entity->base.source_position,
6262 "compound member '%Y' has incomplete type '%T'",
6263 entity->base.symbol, orig_type);
6267 if (token.type != ',')
6274 anonymous_entity = NULL;
6277 static void parse_compound_type_entries(compound_t *compound)
6280 add_anchor_token('}');
6282 while (token.type != '}') {
6283 if (token.type == T_EOF) {
6284 errorf(HERE, "EOF while parsing struct");
6287 declaration_specifiers_t specifiers;
6288 memset(&specifiers, 0, sizeof(specifiers));
6289 parse_declaration_specifiers(&specifiers);
6291 parse_compound_declarators(compound, &specifiers);
6293 rem_anchor_token('}');
6297 compound->complete = true;
6300 static type_t *parse_typename(void)
6302 declaration_specifiers_t specifiers;
6303 memset(&specifiers, 0, sizeof(specifiers));
6304 parse_declaration_specifiers(&specifiers);
6305 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6306 /* TODO: improve error message, user does probably not know what a
6307 * storage class is...
6309 errorf(HERE, "typename may not have a storage class");
6312 type_t *result = parse_abstract_declarator(specifiers.type);
6320 typedef expression_t* (*parse_expression_function)(void);
6321 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6323 typedef struct expression_parser_function_t expression_parser_function_t;
6324 struct expression_parser_function_t {
6325 parse_expression_function parser;
6326 unsigned infix_precedence;
6327 parse_expression_infix_function infix_parser;
6330 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6333 * Prints an error message if an expression was expected but not read
6335 static expression_t *expected_expression_error(void)
6337 /* skip the error message if the error token was read */
6338 if (token.type != T_ERROR) {
6339 errorf(HERE, "expected expression, got token '%K'", &token);
6343 return create_invalid_expression();
6347 * Parse a string constant.
6349 static expression_t *parse_string_const(void)
6352 if (token.type == T_STRING_LITERAL) {
6353 string_t res = token.v.string;
6355 while (token.type == T_STRING_LITERAL) {
6356 res = concat_strings(&res, &token.v.string);
6359 if (token.type != T_WIDE_STRING_LITERAL) {
6360 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6361 /* note: that we use type_char_ptr here, which is already the
6362 * automatic converted type. revert_automatic_type_conversion
6363 * will construct the array type */
6364 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6365 cnst->string.value = res;
6369 wres = concat_string_wide_string(&res, &token.v.wide_string);
6371 wres = token.v.wide_string;
6376 switch (token.type) {
6377 case T_WIDE_STRING_LITERAL:
6378 wres = concat_wide_strings(&wres, &token.v.wide_string);
6381 case T_STRING_LITERAL:
6382 wres = concat_wide_string_string(&wres, &token.v.string);
6386 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6387 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6388 cnst->wide_string.value = wres;
6397 * Parse a boolean constant.
6399 static expression_t *parse_bool_const(bool value)
6401 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6402 cnst->base.type = type_bool;
6403 cnst->conste.v.int_value = value;
6411 * Parse an integer constant.
6413 static expression_t *parse_int_const(void)
6415 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6416 cnst->base.type = token.datatype;
6417 cnst->conste.v.int_value = token.v.intvalue;
6425 * Parse a character constant.
6427 static expression_t *parse_character_constant(void)
6429 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6430 cnst->base.type = token.datatype;
6431 cnst->conste.v.character = token.v.string;
6433 if (cnst->conste.v.character.size != 1) {
6435 errorf(HERE, "more than 1 character in character constant");
6436 } else if (warning.multichar) {
6437 warningf(HERE, "multi-character character constant");
6446 * Parse a wide character constant.
6448 static expression_t *parse_wide_character_constant(void)
6450 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6451 cnst->base.type = token.datatype;
6452 cnst->conste.v.wide_character = token.v.wide_string;
6454 if (cnst->conste.v.wide_character.size != 1) {
6456 errorf(HERE, "more than 1 character in character constant");
6457 } else if (warning.multichar) {
6458 warningf(HERE, "multi-character character constant");
6467 * Parse a float constant.
6469 static expression_t *parse_float_const(void)
6471 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6472 cnst->base.type = token.datatype;
6473 cnst->conste.v.float_value = token.v.floatvalue;
6480 static entity_t *create_implicit_function(symbol_t *symbol,
6481 const source_position_t *source_position)
6483 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6484 ntype->function.return_type = type_int;
6485 ntype->function.unspecified_parameters = true;
6487 type_t *type = typehash_insert(ntype);
6488 if (type != ntype) {
6492 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6493 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6494 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6495 entity->declaration.type = type;
6496 entity->declaration.implicit = true;
6497 entity->base.symbol = symbol;
6498 entity->base.source_position = *source_position;
6500 bool strict_prototypes_old = warning.strict_prototypes;
6501 warning.strict_prototypes = false;
6502 record_entity(entity, false);
6503 warning.strict_prototypes = strict_prototypes_old;
6509 * Creates a return_type (func)(argument_type) function type if not
6512 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6513 type_t *argument_type2)
6515 function_parameter_t *parameter2
6516 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6517 memset(parameter2, 0, sizeof(parameter2[0]));
6518 parameter2->type = argument_type2;
6520 function_parameter_t *parameter1
6521 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6522 memset(parameter1, 0, sizeof(parameter1[0]));
6523 parameter1->type = argument_type1;
6524 parameter1->next = parameter2;
6526 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6527 type->function.return_type = return_type;
6528 type->function.parameters = parameter1;
6530 type_t *result = typehash_insert(type);
6531 if (result != type) {
6539 * Creates a return_type (func)(argument_type) function type if not
6542 * @param return_type the return type
6543 * @param argument_type the argument type
6545 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6547 function_parameter_t *parameter
6548 = obstack_alloc(type_obst, sizeof(parameter[0]));
6549 memset(parameter, 0, sizeof(parameter[0]));
6550 parameter->type = argument_type;
6552 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6553 type->function.return_type = return_type;
6554 type->function.parameters = parameter;
6556 type_t *result = typehash_insert(type);
6557 if (result != type) {
6564 static type_t *make_function_0_type(type_t *return_type)
6566 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6567 type->function.return_type = return_type;
6568 type->function.parameters = NULL;
6570 type_t *result = typehash_insert(type);
6571 if (result != type) {
6579 * Creates a function type for some function like builtins.
6581 * @param symbol the symbol describing the builtin
6583 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6585 switch (symbol->ID) {
6586 case T___builtin_alloca:
6587 return make_function_1_type(type_void_ptr, type_size_t);
6588 case T___builtin_huge_val:
6589 return make_function_0_type(type_double);
6590 case T___builtin_inf:
6591 return make_function_0_type(type_double);
6592 case T___builtin_inff:
6593 return make_function_0_type(type_float);
6594 case T___builtin_infl:
6595 return make_function_0_type(type_long_double);
6596 case T___builtin_nan:
6597 return make_function_1_type(type_double, type_char_ptr);
6598 case T___builtin_nanf:
6599 return make_function_1_type(type_float, type_char_ptr);
6600 case T___builtin_nanl:
6601 return make_function_1_type(type_long_double, type_char_ptr);
6602 case T___builtin_va_end:
6603 return make_function_1_type(type_void, type_valist);
6604 case T___builtin_expect:
6605 return make_function_2_type(type_long, type_long, type_long);
6607 internal_errorf(HERE, "not implemented builtin symbol found");
6612 * Performs automatic type cast as described in § 6.3.2.1.
6614 * @param orig_type the original type
6616 static type_t *automatic_type_conversion(type_t *orig_type)
6618 type_t *type = skip_typeref(orig_type);
6619 if (is_type_array(type)) {
6620 array_type_t *array_type = &type->array;
6621 type_t *element_type = array_type->element_type;
6622 unsigned qualifiers = array_type->base.qualifiers;
6624 return make_pointer_type(element_type, qualifiers);
6627 if (is_type_function(type)) {
6628 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6635 * reverts the automatic casts of array to pointer types and function
6636 * to function-pointer types as defined § 6.3.2.1
6638 type_t *revert_automatic_type_conversion(const expression_t *expression)
6640 switch (expression->kind) {
6641 case EXPR_REFERENCE: {
6642 entity_t *entity = expression->reference.entity;
6643 if (is_declaration(entity)) {
6644 return entity->declaration.type;
6645 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6646 return entity->enum_value.enum_type;
6648 panic("no declaration or enum in reference");
6653 entity_t *entity = expression->select.compound_entry;
6654 assert(is_declaration(entity));
6655 type_t *type = entity->declaration.type;
6656 return get_qualified_type(type,
6657 expression->base.type->base.qualifiers);
6660 case EXPR_UNARY_DEREFERENCE: {
6661 const expression_t *const value = expression->unary.value;
6662 type_t *const type = skip_typeref(value->base.type);
6663 assert(is_type_pointer(type));
6664 return type->pointer.points_to;
6667 case EXPR_BUILTIN_SYMBOL:
6668 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6670 case EXPR_ARRAY_ACCESS: {
6671 const expression_t *array_ref = expression->array_access.array_ref;
6672 type_t *type_left = skip_typeref(array_ref->base.type);
6673 if (!is_type_valid(type_left))
6675 assert(is_type_pointer(type_left));
6676 return type_left->pointer.points_to;
6679 case EXPR_STRING_LITERAL: {
6680 size_t size = expression->string.value.size;
6681 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6684 case EXPR_WIDE_STRING_LITERAL: {
6685 size_t size = expression->wide_string.value.size;
6686 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6689 case EXPR_COMPOUND_LITERAL:
6690 return expression->compound_literal.type;
6695 return expression->base.type;
6698 static expression_t *parse_reference(void)
6700 symbol_t *const symbol = token.v.symbol;
6702 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6704 if (entity == NULL) {
6705 if (!strict_mode && look_ahead(1)->type == '(') {
6706 /* an implicitly declared function */
6707 if (warning.implicit_function_declaration) {
6708 warningf(HERE, "implicit declaration of function '%Y'",
6712 entity = create_implicit_function(symbol, HERE);
6714 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6715 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6721 if (is_declaration(entity)) {
6722 orig_type = entity->declaration.type;
6723 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6724 orig_type = entity->enum_value.enum_type;
6725 } else if (entity->kind == ENTITY_TYPEDEF) {
6726 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6729 return create_invalid_expression();
6731 panic("expected declaration or enum value in reference");
6734 /* we always do the auto-type conversions; the & and sizeof parser contains
6735 * code to revert this! */
6736 type_t *type = automatic_type_conversion(orig_type);
6738 expression_kind_t kind = EXPR_REFERENCE;
6739 if (entity->kind == ENTITY_ENUM_VALUE)
6740 kind = EXPR_REFERENCE_ENUM_VALUE;
6742 expression_t *expression = allocate_expression_zero(kind);
6743 expression->reference.entity = entity;
6744 expression->base.type = type;
6746 /* this declaration is used */
6747 if (is_declaration(entity)) {
6748 entity->declaration.used = true;
6751 if (entity->base.parent_scope != file_scope
6752 && entity->base.parent_scope->depth < current_function->parameters.depth
6753 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6754 if (entity->kind == ENTITY_VARIABLE) {
6755 /* access of a variable from an outer function */
6756 entity->variable.address_taken = true;
6758 current_function->need_closure = true;
6761 /* check for deprecated functions */
6762 if (warning.deprecated_declarations
6763 && is_declaration(entity)
6764 && entity->declaration.modifiers & DM_DEPRECATED) {
6765 declaration_t *declaration = &entity->declaration;
6767 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6768 "function" : "variable";
6770 if (declaration->deprecated_string != NULL) {
6771 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6772 prefix, entity->base.symbol, &entity->base.source_position,
6773 declaration->deprecated_string);
6775 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6776 entity->base.symbol, &entity->base.source_position);
6780 if (warning.init_self && entity == current_init_decl && !in_type_prop
6781 && entity->kind == ENTITY_VARIABLE) {
6782 current_init_decl = NULL;
6783 warningf(HERE, "variable '%#T' is initialized by itself",
6784 entity->declaration.type, entity->base.symbol);
6791 static bool semantic_cast(expression_t *cast)
6793 expression_t *expression = cast->unary.value;
6794 type_t *orig_dest_type = cast->base.type;
6795 type_t *orig_type_right = expression->base.type;
6796 type_t const *dst_type = skip_typeref(orig_dest_type);
6797 type_t const *src_type = skip_typeref(orig_type_right);
6798 source_position_t const *pos = &cast->base.source_position;
6800 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6801 if (dst_type == type_void)
6804 /* only integer and pointer can be casted to pointer */
6805 if (is_type_pointer(dst_type) &&
6806 !is_type_pointer(src_type) &&
6807 !is_type_integer(src_type) &&
6808 is_type_valid(src_type)) {
6809 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6813 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6814 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6818 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6819 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6823 if (warning.cast_qual &&
6824 is_type_pointer(src_type) &&
6825 is_type_pointer(dst_type)) {
6826 type_t *src = skip_typeref(src_type->pointer.points_to);
6827 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6828 unsigned missing_qualifiers =
6829 src->base.qualifiers & ~dst->base.qualifiers;
6830 if (missing_qualifiers != 0) {
6832 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6833 missing_qualifiers, orig_type_right);
6839 static expression_t *parse_compound_literal(type_t *type)
6841 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6843 parse_initializer_env_t env;
6846 env.must_be_constant = false;
6847 initializer_t *initializer = parse_initializer(&env);
6850 expression->compound_literal.initializer = initializer;
6851 expression->compound_literal.type = type;
6852 expression->base.type = automatic_type_conversion(type);
6858 * Parse a cast expression.
6860 static expression_t *parse_cast(void)
6862 add_anchor_token(')');
6864 source_position_t source_position = token.source_position;
6866 type_t *type = parse_typename();
6868 rem_anchor_token(')');
6871 if (token.type == '{') {
6872 return parse_compound_literal(type);
6875 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6876 cast->base.source_position = source_position;
6878 expression_t *value = parse_sub_expression(PREC_CAST);
6879 cast->base.type = type;
6880 cast->unary.value = value;
6882 if (! semantic_cast(cast)) {
6883 /* TODO: record the error in the AST. else it is impossible to detect it */
6888 return create_invalid_expression();
6892 * Parse a statement expression.
6894 static expression_t *parse_statement_expression(void)
6896 add_anchor_token(')');
6898 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6900 statement_t *statement = parse_compound_statement(true);
6901 expression->statement.statement = statement;
6903 /* find last statement and use its type */
6904 type_t *type = type_void;
6905 const statement_t *stmt = statement->compound.statements;
6907 while (stmt->base.next != NULL)
6908 stmt = stmt->base.next;
6910 if (stmt->kind == STATEMENT_EXPRESSION) {
6911 type = stmt->expression.expression->base.type;
6913 } else if (warning.other) {
6914 warningf(&expression->base.source_position, "empty statement expression ({})");
6916 expression->base.type = type;
6918 rem_anchor_token(')');
6926 * Parse a parenthesized expression.
6928 static expression_t *parse_parenthesized_expression(void)
6932 switch (token.type) {
6934 /* gcc extension: a statement expression */
6935 return parse_statement_expression();
6939 return parse_cast();
6941 if (is_typedef_symbol(token.v.symbol)) {
6942 return parse_cast();
6946 add_anchor_token(')');
6947 expression_t *result = parse_expression();
6948 rem_anchor_token(')');
6955 static expression_t *parse_function_keyword(void)
6959 if (current_function == NULL) {
6960 errorf(HERE, "'__func__' used outside of a function");
6963 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6964 expression->base.type = type_char_ptr;
6965 expression->funcname.kind = FUNCNAME_FUNCTION;
6972 static expression_t *parse_pretty_function_keyword(void)
6974 if (current_function == NULL) {
6975 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6978 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6979 expression->base.type = type_char_ptr;
6980 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6982 eat(T___PRETTY_FUNCTION__);
6987 static expression_t *parse_funcsig_keyword(void)
6989 if (current_function == NULL) {
6990 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6993 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6994 expression->base.type = type_char_ptr;
6995 expression->funcname.kind = FUNCNAME_FUNCSIG;
7002 static expression_t *parse_funcdname_keyword(void)
7004 if (current_function == NULL) {
7005 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7008 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7009 expression->base.type = type_char_ptr;
7010 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7012 eat(T___FUNCDNAME__);
7017 static designator_t *parse_designator(void)
7019 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7020 result->source_position = *HERE;
7022 if (token.type != T_IDENTIFIER) {
7023 parse_error_expected("while parsing member designator",
7024 T_IDENTIFIER, NULL);
7027 result->symbol = token.v.symbol;
7030 designator_t *last_designator = result;
7032 if (token.type == '.') {
7034 if (token.type != T_IDENTIFIER) {
7035 parse_error_expected("while parsing member designator",
7036 T_IDENTIFIER, NULL);
7039 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7040 designator->source_position = *HERE;
7041 designator->symbol = token.v.symbol;
7044 last_designator->next = designator;
7045 last_designator = designator;
7048 if (token.type == '[') {
7050 add_anchor_token(']');
7051 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7052 designator->source_position = *HERE;
7053 designator->array_index = parse_expression();
7054 rem_anchor_token(']');
7056 if (designator->array_index == NULL) {
7060 last_designator->next = designator;
7061 last_designator = designator;
7073 * Parse the __builtin_offsetof() expression.
7075 static expression_t *parse_offsetof(void)
7077 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7078 expression->base.type = type_size_t;
7080 eat(T___builtin_offsetof);
7083 add_anchor_token(',');
7084 type_t *type = parse_typename();
7085 rem_anchor_token(',');
7087 add_anchor_token(')');
7088 designator_t *designator = parse_designator();
7089 rem_anchor_token(')');
7092 expression->offsetofe.type = type;
7093 expression->offsetofe.designator = designator;
7096 memset(&path, 0, sizeof(path));
7097 path.top_type = type;
7098 path.path = NEW_ARR_F(type_path_entry_t, 0);
7100 descend_into_subtype(&path);
7102 if (!walk_designator(&path, designator, true)) {
7103 return create_invalid_expression();
7106 DEL_ARR_F(path.path);
7110 return create_invalid_expression();
7114 * Parses a _builtin_va_start() expression.
7116 static expression_t *parse_va_start(void)
7118 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7120 eat(T___builtin_va_start);
7123 add_anchor_token(',');
7124 expression->va_starte.ap = parse_assignment_expression();
7125 rem_anchor_token(',');
7127 expression_t *const expr = parse_assignment_expression();
7128 if (expr->kind == EXPR_REFERENCE) {
7129 entity_t *const entity = expr->reference.entity;
7130 if (entity->base.parent_scope != ¤t_function->parameters
7131 || entity->base.next != NULL
7132 || entity->kind != ENTITY_VARIABLE) {
7133 errorf(&expr->base.source_position,
7134 "second argument of 'va_start' must be last parameter of the current function");
7136 expression->va_starte.parameter = &entity->variable;
7143 return create_invalid_expression();
7147 * Parses a _builtin_va_arg() expression.
7149 static expression_t *parse_va_arg(void)
7151 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7153 eat(T___builtin_va_arg);
7156 expression->va_arge.ap = parse_assignment_expression();
7158 expression->base.type = parse_typename();
7163 return create_invalid_expression();
7166 static expression_t *parse_builtin_symbol(void)
7168 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7170 symbol_t *symbol = token.v.symbol;
7172 expression->builtin_symbol.symbol = symbol;
7175 type_t *type = get_builtin_symbol_type(symbol);
7176 type = automatic_type_conversion(type);
7178 expression->base.type = type;
7183 * Parses a __builtin_constant() expression.
7185 static expression_t *parse_builtin_constant(void)
7187 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7189 eat(T___builtin_constant_p);
7192 add_anchor_token(')');
7193 expression->builtin_constant.value = parse_assignment_expression();
7194 rem_anchor_token(')');
7196 expression->base.type = type_int;
7200 return create_invalid_expression();
7204 * Parses a __builtin_prefetch() expression.
7206 static expression_t *parse_builtin_prefetch(void)
7208 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7210 eat(T___builtin_prefetch);
7213 add_anchor_token(')');
7214 expression->builtin_prefetch.adr = parse_assignment_expression();
7215 if (token.type == ',') {
7217 expression->builtin_prefetch.rw = parse_assignment_expression();
7219 if (token.type == ',') {
7221 expression->builtin_prefetch.locality = parse_assignment_expression();
7223 rem_anchor_token(')');
7225 expression->base.type = type_void;
7229 return create_invalid_expression();
7233 * Parses a __builtin_is_*() compare expression.
7235 static expression_t *parse_compare_builtin(void)
7237 expression_t *expression;
7239 switch (token.type) {
7240 case T___builtin_isgreater:
7241 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7243 case T___builtin_isgreaterequal:
7244 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7246 case T___builtin_isless:
7247 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7249 case T___builtin_islessequal:
7250 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7252 case T___builtin_islessgreater:
7253 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7255 case T___builtin_isunordered:
7256 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7259 internal_errorf(HERE, "invalid compare builtin found");
7261 expression->base.source_position = *HERE;
7265 expression->binary.left = parse_assignment_expression();
7267 expression->binary.right = parse_assignment_expression();
7270 type_t *const orig_type_left = expression->binary.left->base.type;
7271 type_t *const orig_type_right = expression->binary.right->base.type;
7273 type_t *const type_left = skip_typeref(orig_type_left);
7274 type_t *const type_right = skip_typeref(orig_type_right);
7275 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7276 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7277 type_error_incompatible("invalid operands in comparison",
7278 &expression->base.source_position, orig_type_left, orig_type_right);
7281 semantic_comparison(&expression->binary);
7286 return create_invalid_expression();
7291 * Parses a __builtin_expect() expression.
7293 static expression_t *parse_builtin_expect(void)
7295 expression_t *expression
7296 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7298 eat(T___builtin_expect);
7301 expression->binary.left = parse_assignment_expression();
7303 expression->binary.right = parse_constant_expression();
7306 expression->base.type = expression->binary.left->base.type;
7310 return create_invalid_expression();
7315 * Parses a MS assume() expression.
7317 static expression_t *parse_assume(void)
7319 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7324 add_anchor_token(')');
7325 expression->unary.value = parse_assignment_expression();
7326 rem_anchor_token(')');
7329 expression->base.type = type_void;
7332 return create_invalid_expression();
7336 * Return the declaration for a given label symbol or create a new one.
7338 * @param symbol the symbol of the label
7340 static label_t *get_label(symbol_t *symbol)
7343 assert(current_function != NULL);
7345 label = get_entity(symbol, NAMESPACE_LABEL);
7346 /* if we found a local label, we already created the declaration */
7347 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7348 if (label->base.parent_scope != current_scope) {
7349 assert(label->base.parent_scope->depth < current_scope->depth);
7350 current_function->goto_to_outer = true;
7352 return &label->label;
7355 label = get_entity(symbol, NAMESPACE_LABEL);
7356 /* if we found a label in the same function, then we already created the
7359 && label->base.parent_scope == ¤t_function->parameters) {
7360 return &label->label;
7363 /* otherwise we need to create a new one */
7364 label = allocate_entity_zero(ENTITY_LABEL);
7365 label->base.namespc = NAMESPACE_LABEL;
7366 label->base.symbol = symbol;
7370 return &label->label;
7374 * Parses a GNU && label address expression.
7376 static expression_t *parse_label_address(void)
7378 source_position_t source_position = token.source_position;
7380 if (token.type != T_IDENTIFIER) {
7381 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7384 symbol_t *symbol = token.v.symbol;
7387 label_t *label = get_label(symbol);
7389 label->address_taken = true;
7391 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7392 expression->base.source_position = source_position;
7394 /* label address is threaten as a void pointer */
7395 expression->base.type = type_void_ptr;
7396 expression->label_address.label = label;
7399 return create_invalid_expression();
7403 * Parse a microsoft __noop expression.
7405 static expression_t *parse_noop_expression(void)
7407 /* the result is a (int)0 */
7408 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7409 cnst->base.type = type_int;
7410 cnst->conste.v.int_value = 0;
7411 cnst->conste.is_ms_noop = true;
7415 if (token.type == '(') {
7416 /* parse arguments */
7418 add_anchor_token(')');
7419 add_anchor_token(',');
7421 if (token.type != ')') {
7423 (void)parse_assignment_expression();
7424 if (token.type != ',')
7430 rem_anchor_token(',');
7431 rem_anchor_token(')');
7439 * Parses a primary expression.
7441 static expression_t *parse_primary_expression(void)
7443 switch (token.type) {
7444 case T_false: return parse_bool_const(false);
7445 case T_true: return parse_bool_const(true);
7446 case T_INTEGER: return parse_int_const();
7447 case T_CHARACTER_CONSTANT: return parse_character_constant();
7448 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7449 case T_FLOATINGPOINT: return parse_float_const();
7450 case T_STRING_LITERAL:
7451 case T_WIDE_STRING_LITERAL: return parse_string_const();
7452 case T_IDENTIFIER: return parse_reference();
7453 case T___FUNCTION__:
7454 case T___func__: return parse_function_keyword();
7455 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7456 case T___FUNCSIG__: return parse_funcsig_keyword();
7457 case T___FUNCDNAME__: return parse_funcdname_keyword();
7458 case T___builtin_offsetof: return parse_offsetof();
7459 case T___builtin_va_start: return parse_va_start();
7460 case T___builtin_va_arg: return parse_va_arg();
7461 case T___builtin_expect:
7462 case T___builtin_alloca:
7463 case T___builtin_inf:
7464 case T___builtin_inff:
7465 case T___builtin_infl:
7466 case T___builtin_nan:
7467 case T___builtin_nanf:
7468 case T___builtin_nanl:
7469 case T___builtin_huge_val:
7470 case T___builtin_va_end: return parse_builtin_symbol();
7471 case T___builtin_isgreater:
7472 case T___builtin_isgreaterequal:
7473 case T___builtin_isless:
7474 case T___builtin_islessequal:
7475 case T___builtin_islessgreater:
7476 case T___builtin_isunordered: return parse_compare_builtin();
7477 case T___builtin_constant_p: return parse_builtin_constant();
7478 case T___builtin_prefetch: return parse_builtin_prefetch();
7479 case T__assume: return parse_assume();
7482 return parse_label_address();
7485 case '(': return parse_parenthesized_expression();
7486 case T___noop: return parse_noop_expression();
7489 errorf(HERE, "unexpected token %K, expected an expression", &token);
7490 return create_invalid_expression();
7494 * Check if the expression has the character type and issue a warning then.
7496 static void check_for_char_index_type(const expression_t *expression)
7498 type_t *const type = expression->base.type;
7499 const type_t *const base_type = skip_typeref(type);
7501 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7502 warning.char_subscripts) {
7503 warningf(&expression->base.source_position,
7504 "array subscript has type '%T'", type);
7508 static expression_t *parse_array_expression(expression_t *left)
7510 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7513 add_anchor_token(']');
7515 expression_t *inside = parse_expression();
7517 type_t *const orig_type_left = left->base.type;
7518 type_t *const orig_type_inside = inside->base.type;
7520 type_t *const type_left = skip_typeref(orig_type_left);
7521 type_t *const type_inside = skip_typeref(orig_type_inside);
7523 type_t *return_type;
7524 array_access_expression_t *array_access = &expression->array_access;
7525 if (is_type_pointer(type_left)) {
7526 return_type = type_left->pointer.points_to;
7527 array_access->array_ref = left;
7528 array_access->index = inside;
7529 check_for_char_index_type(inside);
7530 } else if (is_type_pointer(type_inside)) {
7531 return_type = type_inside->pointer.points_to;
7532 array_access->array_ref = inside;
7533 array_access->index = left;
7534 array_access->flipped = true;
7535 check_for_char_index_type(left);
7537 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7539 "array access on object with non-pointer types '%T', '%T'",
7540 orig_type_left, orig_type_inside);
7542 return_type = type_error_type;
7543 array_access->array_ref = left;
7544 array_access->index = inside;
7547 expression->base.type = automatic_type_conversion(return_type);
7549 rem_anchor_token(']');
7555 static expression_t *parse_typeprop(expression_kind_t const kind)
7557 expression_t *tp_expression = allocate_expression_zero(kind);
7558 tp_expression->base.type = type_size_t;
7560 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7562 /* we only refer to a type property, mark this case */
7563 bool old = in_type_prop;
7564 in_type_prop = true;
7567 expression_t *expression;
7568 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7570 add_anchor_token(')');
7571 orig_type = parse_typename();
7572 rem_anchor_token(')');
7575 if (token.type == '{') {
7576 /* It was not sizeof(type) after all. It is sizeof of an expression
7577 * starting with a compound literal */
7578 expression = parse_compound_literal(orig_type);
7579 goto typeprop_expression;
7582 expression = parse_sub_expression(PREC_UNARY);
7584 typeprop_expression:
7585 tp_expression->typeprop.tp_expression = expression;
7587 orig_type = revert_automatic_type_conversion(expression);
7588 expression->base.type = orig_type;
7591 tp_expression->typeprop.type = orig_type;
7592 type_t const* const type = skip_typeref(orig_type);
7593 char const* const wrong_type =
7594 is_type_incomplete(type) ? "incomplete" :
7595 type->kind == TYPE_FUNCTION ? "function designator" :
7596 type->kind == TYPE_BITFIELD ? "bitfield" :
7598 if (wrong_type != NULL) {
7599 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7600 errorf(&tp_expression->base.source_position,
7601 "operand of %s expression must not be of %s type '%T'",
7602 what, wrong_type, orig_type);
7607 return tp_expression;
7610 static expression_t *parse_sizeof(void)
7612 return parse_typeprop(EXPR_SIZEOF);
7615 static expression_t *parse_alignof(void)
7617 return parse_typeprop(EXPR_ALIGNOF);
7620 static expression_t *parse_select_expression(expression_t *compound)
7622 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7623 select->select.compound = compound;
7625 assert(token.type == '.' || token.type == T_MINUSGREATER);
7626 bool is_pointer = (token.type == T_MINUSGREATER);
7629 if (token.type != T_IDENTIFIER) {
7630 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7633 symbol_t *symbol = token.v.symbol;
7636 type_t *const orig_type = compound->base.type;
7637 type_t *const type = skip_typeref(orig_type);
7640 bool saw_error = false;
7641 if (is_type_pointer(type)) {
7644 "request for member '%Y' in something not a struct or union, but '%T'",
7648 type_left = skip_typeref(type->pointer.points_to);
7650 if (is_pointer && is_type_valid(type)) {
7651 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7658 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7659 type_left->kind == TYPE_COMPOUND_UNION) {
7660 compound_t *compound = type_left->compound.compound;
7662 if (!compound->complete) {
7663 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7665 goto create_error_entry;
7668 entry = find_compound_entry(compound, symbol);
7669 if (entry == NULL) {
7670 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7671 goto create_error_entry;
7674 if (is_type_valid(type_left) && !saw_error) {
7676 "request for member '%Y' in something not a struct or union, but '%T'",
7680 return create_invalid_expression();
7683 assert(is_declaration(entry));
7684 select->select.compound_entry = entry;
7686 type_t *entry_type = entry->declaration.type;
7688 = get_qualified_type(entry_type, type_left->base.qualifiers);
7690 /* we always do the auto-type conversions; the & and sizeof parser contains
7691 * code to revert this! */
7692 select->base.type = automatic_type_conversion(res_type);
7694 type_t *skipped = skip_typeref(res_type);
7695 if (skipped->kind == TYPE_BITFIELD) {
7696 select->base.type = skipped->bitfield.base_type;
7702 static void check_call_argument(const function_parameter_t *parameter,
7703 call_argument_t *argument, unsigned pos)
7705 type_t *expected_type = parameter->type;
7706 type_t *expected_type_skip = skip_typeref(expected_type);
7707 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7708 expression_t *arg_expr = argument->expression;
7709 type_t *arg_type = skip_typeref(arg_expr->base.type);
7711 /* handle transparent union gnu extension */
7712 if (is_type_union(expected_type_skip)
7713 && (expected_type_skip->base.modifiers
7714 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7715 compound_t *union_decl = expected_type_skip->compound.compound;
7716 type_t *best_type = NULL;
7717 entity_t *entry = union_decl->members.entities;
7718 for ( ; entry != NULL; entry = entry->base.next) {
7719 assert(is_declaration(entry));
7720 type_t *decl_type = entry->declaration.type;
7721 error = semantic_assign(decl_type, arg_expr);
7722 if (error == ASSIGN_ERROR_INCOMPATIBLE
7723 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7726 if (error == ASSIGN_SUCCESS) {
7727 best_type = decl_type;
7728 } else if (best_type == NULL) {
7729 best_type = decl_type;
7733 if (best_type != NULL) {
7734 expected_type = best_type;
7738 error = semantic_assign(expected_type, arg_expr);
7739 argument->expression = create_implicit_cast(argument->expression,
7742 if (error != ASSIGN_SUCCESS) {
7743 /* report exact scope in error messages (like "in argument 3") */
7745 snprintf(buf, sizeof(buf), "call argument %u", pos);
7746 report_assign_error(error, expected_type, arg_expr, buf,
7747 &arg_expr->base.source_position);
7748 } else if (warning.traditional || warning.conversion) {
7749 type_t *const promoted_type = get_default_promoted_type(arg_type);
7750 if (!types_compatible(expected_type_skip, promoted_type) &&
7751 !types_compatible(expected_type_skip, type_void_ptr) &&
7752 !types_compatible(type_void_ptr, promoted_type)) {
7753 /* Deliberately show the skipped types in this warning */
7754 warningf(&arg_expr->base.source_position,
7755 "passing call argument %u as '%T' rather than '%T' due to prototype",
7756 pos, expected_type_skip, promoted_type);
7762 * Parse a call expression, ie. expression '( ... )'.
7764 * @param expression the function address
7766 static expression_t *parse_call_expression(expression_t *expression)
7768 expression_t *result = allocate_expression_zero(EXPR_CALL);
7769 call_expression_t *call = &result->call;
7770 call->function = expression;
7772 type_t *const orig_type = expression->base.type;
7773 type_t *const type = skip_typeref(orig_type);
7775 function_type_t *function_type = NULL;
7776 if (is_type_pointer(type)) {
7777 type_t *const to_type = skip_typeref(type->pointer.points_to);
7779 if (is_type_function(to_type)) {
7780 function_type = &to_type->function;
7781 call->base.type = function_type->return_type;
7785 if (function_type == NULL && is_type_valid(type)) {
7786 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7789 /* parse arguments */
7791 add_anchor_token(')');
7792 add_anchor_token(',');
7794 if (token.type != ')') {
7795 call_argument_t *last_argument = NULL;
7798 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7800 argument->expression = parse_assignment_expression();
7801 if (last_argument == NULL) {
7802 call->arguments = argument;
7804 last_argument->next = argument;
7806 last_argument = argument;
7808 if (token.type != ',')
7813 rem_anchor_token(',');
7814 rem_anchor_token(')');
7817 if (function_type == NULL)
7820 function_parameter_t *parameter = function_type->parameters;
7821 call_argument_t *argument = call->arguments;
7822 if (!function_type->unspecified_parameters) {
7823 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7824 parameter = parameter->next, argument = argument->next) {
7825 check_call_argument(parameter, argument, ++pos);
7828 if (parameter != NULL) {
7829 errorf(HERE, "too few arguments to function '%E'", expression);
7830 } else if (argument != NULL && !function_type->variadic) {
7831 errorf(HERE, "too many arguments to function '%E'", expression);
7835 /* do default promotion */
7836 for (; argument != NULL; argument = argument->next) {
7837 type_t *type = argument->expression->base.type;
7839 type = get_default_promoted_type(type);
7841 argument->expression
7842 = create_implicit_cast(argument->expression, type);
7845 check_format(&result->call);
7847 if (warning.aggregate_return &&
7848 is_type_compound(skip_typeref(function_type->return_type))) {
7849 warningf(&result->base.source_position,
7850 "function call has aggregate value");
7857 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7859 static bool same_compound_type(const type_t *type1, const type_t *type2)
7862 is_type_compound(type1) &&
7863 type1->kind == type2->kind &&
7864 type1->compound.compound == type2->compound.compound;
7867 static expression_t const *get_reference_address(expression_t const *expr)
7869 bool regular_take_address = true;
7871 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7872 expr = expr->unary.value;
7874 regular_take_address = false;
7877 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7880 expr = expr->unary.value;
7883 if (expr->kind != EXPR_REFERENCE)
7886 /* special case for functions which are automatically converted to a
7887 * pointer to function without an extra TAKE_ADDRESS operation */
7888 if (!regular_take_address &&
7889 expr->reference.entity->kind != ENTITY_FUNCTION) {
7896 static void warn_reference_address_as_bool(expression_t const* expr)
7898 if (!warning.address)
7901 expr = get_reference_address(expr);
7903 warningf(&expr->base.source_position,
7904 "the address of '%Y' will always evaluate as 'true'",
7905 expr->reference.entity->base.symbol);
7909 static void semantic_condition(expression_t const *const expr,
7910 char const *const context)
7912 type_t *const type = skip_typeref(expr->base.type);
7913 if (is_type_scalar(type)) {
7914 warn_reference_address_as_bool(expr);
7915 } else if (is_type_valid(type)) {
7916 errorf(&expr->base.source_position,
7917 "%s must have scalar type", context);
7922 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7924 * @param expression the conditional expression
7926 static expression_t *parse_conditional_expression(expression_t *expression)
7928 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7930 conditional_expression_t *conditional = &result->conditional;
7931 conditional->condition = expression;
7934 add_anchor_token(':');
7936 /* §6.5.15:2 The first operand shall have scalar type. */
7937 semantic_condition(expression, "condition of conditional operator");
7939 expression_t *true_expression = expression;
7940 bool gnu_cond = false;
7941 if (GNU_MODE && token.type == ':') {
7944 true_expression = parse_expression();
7946 rem_anchor_token(':');
7948 expression_t *false_expression =
7949 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7951 type_t *const orig_true_type = true_expression->base.type;
7952 type_t *const orig_false_type = false_expression->base.type;
7953 type_t *const true_type = skip_typeref(orig_true_type);
7954 type_t *const false_type = skip_typeref(orig_false_type);
7957 type_t *result_type;
7958 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7959 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7960 /* ISO/IEC 14882:1998(E) §5.16:2 */
7961 if (true_expression->kind == EXPR_UNARY_THROW) {
7962 result_type = false_type;
7963 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7964 result_type = true_type;
7966 if (warning.other && (
7967 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7968 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7970 warningf(&conditional->base.source_position,
7971 "ISO C forbids conditional expression with only one void side");
7973 result_type = type_void;
7975 } else if (is_type_arithmetic(true_type)
7976 && is_type_arithmetic(false_type)) {
7977 result_type = semantic_arithmetic(true_type, false_type);
7979 true_expression = create_implicit_cast(true_expression, result_type);
7980 false_expression = create_implicit_cast(false_expression, result_type);
7982 conditional->true_expression = true_expression;
7983 conditional->false_expression = false_expression;
7984 conditional->base.type = result_type;
7985 } else if (same_compound_type(true_type, false_type)) {
7986 /* just take 1 of the 2 types */
7987 result_type = true_type;
7988 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7989 type_t *pointer_type;
7991 expression_t *other_expression;
7992 if (is_type_pointer(true_type) &&
7993 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7994 pointer_type = true_type;
7995 other_type = false_type;
7996 other_expression = false_expression;
7998 pointer_type = false_type;
7999 other_type = true_type;
8000 other_expression = true_expression;
8003 if (is_null_pointer_constant(other_expression)) {
8004 result_type = pointer_type;
8005 } else if (is_type_pointer(other_type)) {
8006 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8007 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8010 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8011 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8013 } else if (types_compatible(get_unqualified_type(to1),
8014 get_unqualified_type(to2))) {
8017 if (warning.other) {
8018 warningf(&conditional->base.source_position,
8019 "pointer types '%T' and '%T' in conditional expression are incompatible",
8020 true_type, false_type);
8025 type_t *const type =
8026 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8027 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8028 } else if (is_type_integer(other_type)) {
8029 if (warning.other) {
8030 warningf(&conditional->base.source_position,
8031 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8033 result_type = pointer_type;
8035 if (is_type_valid(other_type)) {
8036 type_error_incompatible("while parsing conditional",
8037 &expression->base.source_position, true_type, false_type);
8039 result_type = type_error_type;
8042 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8043 type_error_incompatible("while parsing conditional",
8044 &conditional->base.source_position, true_type,
8047 result_type = type_error_type;
8050 conditional->true_expression
8051 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8052 conditional->false_expression
8053 = create_implicit_cast(false_expression, result_type);
8054 conditional->base.type = result_type;
8057 return create_invalid_expression();
8061 * Parse an extension expression.
8063 static expression_t *parse_extension(void)
8065 eat(T___extension__);
8067 bool old_gcc_extension = in_gcc_extension;
8068 in_gcc_extension = true;
8069 expression_t *expression = parse_sub_expression(PREC_UNARY);
8070 in_gcc_extension = old_gcc_extension;
8075 * Parse a __builtin_classify_type() expression.
8077 static expression_t *parse_builtin_classify_type(void)
8079 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8080 result->base.type = type_int;
8082 eat(T___builtin_classify_type);
8085 add_anchor_token(')');
8086 expression_t *expression = parse_expression();
8087 rem_anchor_token(')');
8089 result->classify_type.type_expression = expression;
8093 return create_invalid_expression();
8097 * Parse a delete expression
8098 * ISO/IEC 14882:1998(E) §5.3.5
8100 static expression_t *parse_delete(void)
8102 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8103 result->base.type = type_void;
8107 if (token.type == '[') {
8109 result->kind = EXPR_UNARY_DELETE_ARRAY;
8114 expression_t *const value = parse_sub_expression(PREC_CAST);
8115 result->unary.value = value;
8117 type_t *const type = skip_typeref(value->base.type);
8118 if (!is_type_pointer(type)) {
8119 errorf(&value->base.source_position,
8120 "operand of delete must have pointer type");
8121 } else if (warning.other &&
8122 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8123 warningf(&value->base.source_position,
8124 "deleting 'void*' is undefined");
8131 * Parse a throw expression
8132 * ISO/IEC 14882:1998(E) §15:1
8134 static expression_t *parse_throw(void)
8136 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8137 result->base.type = type_void;
8141 expression_t *value = NULL;
8142 switch (token.type) {
8144 value = parse_assignment_expression();
8145 /* ISO/IEC 14882:1998(E) §15.1:3 */
8146 type_t *const orig_type = value->base.type;
8147 type_t *const type = skip_typeref(orig_type);
8148 if (is_type_incomplete(type)) {
8149 errorf(&value->base.source_position,
8150 "cannot throw object of incomplete type '%T'", orig_type);
8151 } else if (is_type_pointer(type)) {
8152 type_t *const points_to = skip_typeref(type->pointer.points_to);
8153 if (is_type_incomplete(points_to) &&
8154 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8155 errorf(&value->base.source_position,
8156 "cannot throw pointer to incomplete type '%T'", orig_type);
8164 result->unary.value = value;
8169 static bool check_pointer_arithmetic(const source_position_t *source_position,
8170 type_t *pointer_type,
8171 type_t *orig_pointer_type)
8173 type_t *points_to = pointer_type->pointer.points_to;
8174 points_to = skip_typeref(points_to);
8176 if (is_type_incomplete(points_to)) {
8177 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8178 errorf(source_position,
8179 "arithmetic with pointer to incomplete type '%T' not allowed",
8182 } else if (warning.pointer_arith) {
8183 warningf(source_position,
8184 "pointer of type '%T' used in arithmetic",
8187 } else if (is_type_function(points_to)) {
8189 errorf(source_position,
8190 "arithmetic with pointer to function type '%T' not allowed",
8193 } else if (warning.pointer_arith) {
8194 warningf(source_position,
8195 "pointer to a function '%T' used in arithmetic",
8202 static bool is_lvalue(const expression_t *expression)
8204 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8205 switch (expression->kind) {
8206 case EXPR_REFERENCE:
8207 case EXPR_ARRAY_ACCESS:
8209 case EXPR_UNARY_DEREFERENCE:
8213 /* Claim it is an lvalue, if the type is invalid. There was a parse
8214 * error before, which maybe prevented properly recognizing it as
8216 return !is_type_valid(skip_typeref(expression->base.type));
8220 static void semantic_incdec(unary_expression_t *expression)
8222 type_t *const orig_type = expression->value->base.type;
8223 type_t *const type = skip_typeref(orig_type);
8224 if (is_type_pointer(type)) {
8225 if (!check_pointer_arithmetic(&expression->base.source_position,
8229 } else if (!is_type_real(type) && is_type_valid(type)) {
8230 /* TODO: improve error message */
8231 errorf(&expression->base.source_position,
8232 "operation needs an arithmetic or pointer type");
8235 if (!is_lvalue(expression->value)) {
8236 /* TODO: improve error message */
8237 errorf(&expression->base.source_position, "lvalue required as operand");
8239 expression->base.type = orig_type;
8242 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8244 type_t *const orig_type = expression->value->base.type;
8245 type_t *const type = skip_typeref(orig_type);
8246 if (!is_type_arithmetic(type)) {
8247 if (is_type_valid(type)) {
8248 /* TODO: improve error message */
8249 errorf(&expression->base.source_position,
8250 "operation needs an arithmetic type");
8255 expression->base.type = orig_type;
8258 static void semantic_unexpr_plus(unary_expression_t *expression)
8260 semantic_unexpr_arithmetic(expression);
8261 if (warning.traditional)
8262 warningf(&expression->base.source_position,
8263 "traditional C rejects the unary plus operator");
8266 static void semantic_not(unary_expression_t *expression)
8268 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8269 semantic_condition(expression->value, "operand of !");
8270 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8273 static void semantic_unexpr_integer(unary_expression_t *expression)
8275 type_t *const orig_type = expression->value->base.type;
8276 type_t *const type = skip_typeref(orig_type);
8277 if (!is_type_integer(type)) {
8278 if (is_type_valid(type)) {
8279 errorf(&expression->base.source_position,
8280 "operand of ~ must be of integer type");
8285 expression->base.type = orig_type;
8288 static void semantic_dereference(unary_expression_t *expression)
8290 type_t *const orig_type = expression->value->base.type;
8291 type_t *const type = skip_typeref(orig_type);
8292 if (!is_type_pointer(type)) {
8293 if (is_type_valid(type)) {
8294 errorf(&expression->base.source_position,
8295 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8300 type_t *result_type = type->pointer.points_to;
8301 result_type = automatic_type_conversion(result_type);
8302 expression->base.type = result_type;
8306 * Record that an address is taken (expression represents an lvalue).
8308 * @param expression the expression
8309 * @param may_be_register if true, the expression might be an register
8311 static void set_address_taken(expression_t *expression, bool may_be_register)
8313 if (expression->kind != EXPR_REFERENCE)
8316 entity_t *const entity = expression->reference.entity;
8318 if (entity->kind != ENTITY_VARIABLE)
8321 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8322 && !may_be_register) {
8323 errorf(&expression->base.source_position,
8324 "address of register variable '%Y' requested",
8325 entity->base.symbol);
8328 entity->variable.address_taken = true;
8332 * Check the semantic of the address taken expression.
8334 static void semantic_take_addr(unary_expression_t *expression)
8336 expression_t *value = expression->value;
8337 value->base.type = revert_automatic_type_conversion(value);
8339 type_t *orig_type = value->base.type;
8340 type_t *type = skip_typeref(orig_type);
8341 if (!is_type_valid(type))
8345 if (!is_lvalue(value)) {
8346 errorf(&expression->base.source_position, "'&' requires an lvalue");
8348 if (type->kind == TYPE_BITFIELD) {
8349 errorf(&expression->base.source_position,
8350 "'&' not allowed on object with bitfield type '%T'",
8354 set_address_taken(value, false);
8356 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8359 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8360 static expression_t *parse_##unexpression_type(void) \
8362 expression_t *unary_expression \
8363 = allocate_expression_zero(unexpression_type); \
8365 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8367 sfunc(&unary_expression->unary); \
8369 return unary_expression; \
8372 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8373 semantic_unexpr_arithmetic)
8374 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8375 semantic_unexpr_plus)
8376 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8378 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8379 semantic_dereference)
8380 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8382 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8383 semantic_unexpr_integer)
8384 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8386 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8389 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8391 static expression_t *parse_##unexpression_type(expression_t *left) \
8393 expression_t *unary_expression \
8394 = allocate_expression_zero(unexpression_type); \
8396 unary_expression->unary.value = left; \
8398 sfunc(&unary_expression->unary); \
8400 return unary_expression; \
8403 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8404 EXPR_UNARY_POSTFIX_INCREMENT,
8406 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8407 EXPR_UNARY_POSTFIX_DECREMENT,
8410 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8412 /* TODO: handle complex + imaginary types */
8414 type_left = get_unqualified_type(type_left);
8415 type_right = get_unqualified_type(type_right);
8417 /* § 6.3.1.8 Usual arithmetic conversions */
8418 if (type_left == type_long_double || type_right == type_long_double) {
8419 return type_long_double;
8420 } else if (type_left == type_double || type_right == type_double) {
8422 } else if (type_left == type_float || type_right == type_float) {
8426 type_left = promote_integer(type_left);
8427 type_right = promote_integer(type_right);
8429 if (type_left == type_right)
8432 bool const signed_left = is_type_signed(type_left);
8433 bool const signed_right = is_type_signed(type_right);
8434 int const rank_left = get_rank(type_left);
8435 int const rank_right = get_rank(type_right);
8437 if (signed_left == signed_right)
8438 return rank_left >= rank_right ? type_left : type_right;
8447 u_rank = rank_right;
8448 u_type = type_right;
8450 s_rank = rank_right;
8451 s_type = type_right;
8456 if (u_rank >= s_rank)
8459 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8461 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8462 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8466 case ATOMIC_TYPE_INT: return type_unsigned_int;
8467 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8468 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8470 default: panic("invalid atomic type");
8475 * Check the semantic restrictions for a binary expression.
8477 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8479 expression_t *const left = expression->left;
8480 expression_t *const right = expression->right;
8481 type_t *const orig_type_left = left->base.type;
8482 type_t *const orig_type_right = right->base.type;
8483 type_t *const type_left = skip_typeref(orig_type_left);
8484 type_t *const type_right = skip_typeref(orig_type_right);
8486 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8487 /* TODO: improve error message */
8488 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8489 errorf(&expression->base.source_position,
8490 "operation needs arithmetic types");
8495 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8496 expression->left = create_implicit_cast(left, arithmetic_type);
8497 expression->right = create_implicit_cast(right, arithmetic_type);
8498 expression->base.type = arithmetic_type;
8501 static void warn_div_by_zero(binary_expression_t const *const expression)
8503 if (!warning.div_by_zero ||
8504 !is_type_integer(expression->base.type))
8507 expression_t const *const right = expression->right;
8508 /* The type of the right operand can be different for /= */
8509 if (is_type_integer(right->base.type) &&
8510 is_constant_expression(right) &&
8511 fold_constant(right) == 0) {
8512 warningf(&expression->base.source_position, "division by zero");
8517 * Check the semantic restrictions for a div/mod expression.
8519 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8520 semantic_binexpr_arithmetic(expression);
8521 warn_div_by_zero(expression);
8524 static void semantic_shift_op(binary_expression_t *expression)
8526 expression_t *const left = expression->left;
8527 expression_t *const right = expression->right;
8528 type_t *const orig_type_left = left->base.type;
8529 type_t *const orig_type_right = right->base.type;
8530 type_t * type_left = skip_typeref(orig_type_left);
8531 type_t * type_right = skip_typeref(orig_type_right);
8533 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8534 /* TODO: improve error message */
8535 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8536 errorf(&expression->base.source_position,
8537 "operands of shift operation must have integer types");
8542 type_left = promote_integer(type_left);
8543 type_right = promote_integer(type_right);
8545 expression->left = create_implicit_cast(left, type_left);
8546 expression->right = create_implicit_cast(right, type_right);
8547 expression->base.type = type_left;
8550 static void semantic_add(binary_expression_t *expression)
8552 expression_t *const left = expression->left;
8553 expression_t *const right = expression->right;
8554 type_t *const orig_type_left = left->base.type;
8555 type_t *const orig_type_right = right->base.type;
8556 type_t *const type_left = skip_typeref(orig_type_left);
8557 type_t *const type_right = skip_typeref(orig_type_right);
8560 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8561 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8562 expression->left = create_implicit_cast(left, arithmetic_type);
8563 expression->right = create_implicit_cast(right, arithmetic_type);
8564 expression->base.type = arithmetic_type;
8566 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8567 check_pointer_arithmetic(&expression->base.source_position,
8568 type_left, orig_type_left);
8569 expression->base.type = type_left;
8570 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8571 check_pointer_arithmetic(&expression->base.source_position,
8572 type_right, orig_type_right);
8573 expression->base.type = type_right;
8574 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8575 errorf(&expression->base.source_position,
8576 "invalid operands to binary + ('%T', '%T')",
8577 orig_type_left, orig_type_right);
8581 static void semantic_sub(binary_expression_t *expression)
8583 expression_t *const left = expression->left;
8584 expression_t *const right = expression->right;
8585 type_t *const orig_type_left = left->base.type;
8586 type_t *const orig_type_right = right->base.type;
8587 type_t *const type_left = skip_typeref(orig_type_left);
8588 type_t *const type_right = skip_typeref(orig_type_right);
8589 source_position_t const *const pos = &expression->base.source_position;
8592 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8593 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8594 expression->left = create_implicit_cast(left, arithmetic_type);
8595 expression->right = create_implicit_cast(right, arithmetic_type);
8596 expression->base.type = arithmetic_type;
8598 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8599 check_pointer_arithmetic(&expression->base.source_position,
8600 type_left, orig_type_left);
8601 expression->base.type = type_left;
8602 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8603 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8604 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8605 if (!types_compatible(unqual_left, unqual_right)) {
8607 "subtracting pointers to incompatible types '%T' and '%T'",
8608 orig_type_left, orig_type_right);
8609 } else if (!is_type_object(unqual_left)) {
8610 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8611 errorf(pos, "subtracting pointers to non-object types '%T'",
8613 } else if (warning.other) {
8614 warningf(pos, "subtracting pointers to void");
8617 expression->base.type = type_ptrdiff_t;
8618 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8619 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8620 orig_type_left, orig_type_right);
8624 static void warn_string_literal_address(expression_t const* expr)
8626 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8627 expr = expr->unary.value;
8628 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8630 expr = expr->unary.value;
8633 if (expr->kind == EXPR_STRING_LITERAL ||
8634 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8635 warningf(&expr->base.source_position,
8636 "comparison with string literal results in unspecified behaviour");
8641 * Check the semantics of comparison expressions.
8643 * @param expression The expression to check.
8645 static void semantic_comparison(binary_expression_t *expression)
8647 expression_t *left = expression->left;
8648 expression_t *right = expression->right;
8650 if (warning.address) {
8651 warn_string_literal_address(left);
8652 warn_string_literal_address(right);
8654 expression_t const* const func_left = get_reference_address(left);
8655 if (func_left != NULL && is_null_pointer_constant(right)) {
8656 warningf(&expression->base.source_position,
8657 "the address of '%Y' will never be NULL",
8658 func_left->reference.entity->base.symbol);
8661 expression_t const* const func_right = get_reference_address(right);
8662 if (func_right != NULL && is_null_pointer_constant(right)) {
8663 warningf(&expression->base.source_position,
8664 "the address of '%Y' will never be NULL",
8665 func_right->reference.entity->base.symbol);
8669 type_t *orig_type_left = left->base.type;
8670 type_t *orig_type_right = right->base.type;
8671 type_t *type_left = skip_typeref(orig_type_left);
8672 type_t *type_right = skip_typeref(orig_type_right);
8674 /* TODO non-arithmetic types */
8675 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8676 /* test for signed vs unsigned compares */
8677 if (warning.sign_compare &&
8678 (expression->base.kind != EXPR_BINARY_EQUAL &&
8679 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8680 (is_type_signed(type_left) != is_type_signed(type_right))) {
8682 /* check if 1 of the operands is a constant, in this case we just
8683 * check wether we can safely represent the resulting constant in
8684 * the type of the other operand. */
8685 expression_t *const_expr = NULL;
8686 expression_t *other_expr = NULL;
8688 if (is_constant_expression(left)) {
8691 } else if (is_constant_expression(right)) {
8696 if (const_expr != NULL) {
8697 type_t *other_type = skip_typeref(other_expr->base.type);
8698 long val = fold_constant(const_expr);
8699 /* TODO: check if val can be represented by other_type */
8703 warningf(&expression->base.source_position,
8704 "comparison between signed and unsigned");
8706 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8707 expression->left = create_implicit_cast(left, arithmetic_type);
8708 expression->right = create_implicit_cast(right, arithmetic_type);
8709 expression->base.type = arithmetic_type;
8710 if (warning.float_equal &&
8711 (expression->base.kind == EXPR_BINARY_EQUAL ||
8712 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8713 is_type_float(arithmetic_type)) {
8714 warningf(&expression->base.source_position,
8715 "comparing floating point with == or != is unsafe");
8717 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8718 /* TODO check compatibility */
8719 } else if (is_type_pointer(type_left)) {
8720 expression->right = create_implicit_cast(right, type_left);
8721 } else if (is_type_pointer(type_right)) {
8722 expression->left = create_implicit_cast(left, type_right);
8723 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8724 type_error_incompatible("invalid operands in comparison",
8725 &expression->base.source_position,
8726 type_left, type_right);
8728 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8732 * Checks if a compound type has constant fields.
8734 static bool has_const_fields(const compound_type_t *type)
8736 compound_t *compound = type->compound;
8737 entity_t *entry = compound->members.entities;
8739 for (; entry != NULL; entry = entry->base.next) {
8740 if (!is_declaration(entry))
8743 const type_t *decl_type = skip_typeref(entry->declaration.type);
8744 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8751 static bool is_valid_assignment_lhs(expression_t const* const left)
8753 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8754 type_t *const type_left = skip_typeref(orig_type_left);
8756 if (!is_lvalue(left)) {
8757 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8762 if (is_type_array(type_left)) {
8763 errorf(HERE, "cannot assign to arrays ('%E')", left);
8766 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8767 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8771 if (is_type_incomplete(type_left)) {
8772 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8773 left, orig_type_left);
8776 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8777 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8778 left, orig_type_left);
8785 static void semantic_arithmetic_assign(binary_expression_t *expression)
8787 expression_t *left = expression->left;
8788 expression_t *right = expression->right;
8789 type_t *orig_type_left = left->base.type;
8790 type_t *orig_type_right = right->base.type;
8792 if (!is_valid_assignment_lhs(left))
8795 type_t *type_left = skip_typeref(orig_type_left);
8796 type_t *type_right = skip_typeref(orig_type_right);
8798 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8799 /* TODO: improve error message */
8800 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8801 errorf(&expression->base.source_position,
8802 "operation needs arithmetic types");
8807 /* combined instructions are tricky. We can't create an implicit cast on
8808 * the left side, because we need the uncasted form for the store.
8809 * The ast2firm pass has to know that left_type must be right_type
8810 * for the arithmetic operation and create a cast by itself */
8811 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8812 expression->right = create_implicit_cast(right, arithmetic_type);
8813 expression->base.type = type_left;
8816 static void semantic_divmod_assign(binary_expression_t *expression)
8818 semantic_arithmetic_assign(expression);
8819 warn_div_by_zero(expression);
8822 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8824 expression_t *const left = expression->left;
8825 expression_t *const right = expression->right;
8826 type_t *const orig_type_left = left->base.type;
8827 type_t *const orig_type_right = right->base.type;
8828 type_t *const type_left = skip_typeref(orig_type_left);
8829 type_t *const type_right = skip_typeref(orig_type_right);
8831 if (!is_valid_assignment_lhs(left))
8834 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8835 /* combined instructions are tricky. We can't create an implicit cast on
8836 * the left side, because we need the uncasted form for the store.
8837 * The ast2firm pass has to know that left_type must be right_type
8838 * for the arithmetic operation and create a cast by itself */
8839 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8840 expression->right = create_implicit_cast(right, arithmetic_type);
8841 expression->base.type = type_left;
8842 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8843 check_pointer_arithmetic(&expression->base.source_position,
8844 type_left, orig_type_left);
8845 expression->base.type = type_left;
8846 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8847 errorf(&expression->base.source_position,
8848 "incompatible types '%T' and '%T' in assignment",
8849 orig_type_left, orig_type_right);
8854 * Check the semantic restrictions of a logical expression.
8856 static void semantic_logical_op(binary_expression_t *expression)
8858 /* §6.5.13:2 Each of the operands shall have scalar type.
8859 * §6.5.14:2 Each of the operands shall have scalar type. */
8860 semantic_condition(expression->left, "left operand of logical operator");
8861 semantic_condition(expression->right, "right operand of logical operator");
8862 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8866 * Check the semantic restrictions of a binary assign expression.
8868 static void semantic_binexpr_assign(binary_expression_t *expression)
8870 expression_t *left = expression->left;
8871 type_t *orig_type_left = left->base.type;
8873 if (!is_valid_assignment_lhs(left))
8876 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8877 report_assign_error(error, orig_type_left, expression->right,
8878 "assignment", &left->base.source_position);
8879 expression->right = create_implicit_cast(expression->right, orig_type_left);
8880 expression->base.type = orig_type_left;
8884 * Determine if the outermost operation (or parts thereof) of the given
8885 * expression has no effect in order to generate a warning about this fact.
8886 * Therefore in some cases this only examines some of the operands of the
8887 * expression (see comments in the function and examples below).
8889 * f() + 23; // warning, because + has no effect
8890 * x || f(); // no warning, because x controls execution of f()
8891 * x ? y : f(); // warning, because y has no effect
8892 * (void)x; // no warning to be able to suppress the warning
8893 * This function can NOT be used for an "expression has definitely no effect"-
8895 static bool expression_has_effect(const expression_t *const expr)
8897 switch (expr->kind) {
8898 case EXPR_UNKNOWN: break;
8899 case EXPR_INVALID: return true; /* do NOT warn */
8900 case EXPR_REFERENCE: return false;
8901 case EXPR_REFERENCE_ENUM_VALUE: return false;
8902 /* suppress the warning for microsoft __noop operations */
8903 case EXPR_CONST: return expr->conste.is_ms_noop;
8904 case EXPR_CHARACTER_CONSTANT: return false;
8905 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8906 case EXPR_STRING_LITERAL: return false;
8907 case EXPR_WIDE_STRING_LITERAL: return false;
8908 case EXPR_LABEL_ADDRESS: return false;
8911 const call_expression_t *const call = &expr->call;
8912 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8915 switch (call->function->builtin_symbol.symbol->ID) {
8916 case T___builtin_va_end: return true;
8917 default: return false;
8921 /* Generate the warning if either the left or right hand side of a
8922 * conditional expression has no effect */
8923 case EXPR_CONDITIONAL: {
8924 const conditional_expression_t *const cond = &expr->conditional;
8926 expression_has_effect(cond->true_expression) &&
8927 expression_has_effect(cond->false_expression);
8930 case EXPR_SELECT: return false;
8931 case EXPR_ARRAY_ACCESS: return false;
8932 case EXPR_SIZEOF: return false;
8933 case EXPR_CLASSIFY_TYPE: return false;
8934 case EXPR_ALIGNOF: return false;
8936 case EXPR_FUNCNAME: return false;
8937 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8938 case EXPR_BUILTIN_CONSTANT_P: return false;
8939 case EXPR_BUILTIN_PREFETCH: return true;
8940 case EXPR_OFFSETOF: return false;
8941 case EXPR_VA_START: return true;
8942 case EXPR_VA_ARG: return true;
8943 case EXPR_STATEMENT: return true; // TODO
8944 case EXPR_COMPOUND_LITERAL: return false;
8946 case EXPR_UNARY_NEGATE: return false;
8947 case EXPR_UNARY_PLUS: return false;
8948 case EXPR_UNARY_BITWISE_NEGATE: return false;
8949 case EXPR_UNARY_NOT: return false;
8950 case EXPR_UNARY_DEREFERENCE: return false;
8951 case EXPR_UNARY_TAKE_ADDRESS: return false;
8952 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8953 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8954 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8955 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8957 /* Treat void casts as if they have an effect in order to being able to
8958 * suppress the warning */
8959 case EXPR_UNARY_CAST: {
8960 type_t *const type = skip_typeref(expr->base.type);
8961 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8964 case EXPR_UNARY_CAST_IMPLICIT: return true;
8965 case EXPR_UNARY_ASSUME: return true;
8966 case EXPR_UNARY_DELETE: return true;
8967 case EXPR_UNARY_DELETE_ARRAY: return true;
8968 case EXPR_UNARY_THROW: return true;
8970 case EXPR_BINARY_ADD: return false;
8971 case EXPR_BINARY_SUB: return false;
8972 case EXPR_BINARY_MUL: return false;
8973 case EXPR_BINARY_DIV: return false;
8974 case EXPR_BINARY_MOD: return false;
8975 case EXPR_BINARY_EQUAL: return false;
8976 case EXPR_BINARY_NOTEQUAL: return false;
8977 case EXPR_BINARY_LESS: return false;
8978 case EXPR_BINARY_LESSEQUAL: return false;
8979 case EXPR_BINARY_GREATER: return false;
8980 case EXPR_BINARY_GREATEREQUAL: return false;
8981 case EXPR_BINARY_BITWISE_AND: return false;
8982 case EXPR_BINARY_BITWISE_OR: return false;
8983 case EXPR_BINARY_BITWISE_XOR: return false;
8984 case EXPR_BINARY_SHIFTLEFT: return false;
8985 case EXPR_BINARY_SHIFTRIGHT: return false;
8986 case EXPR_BINARY_ASSIGN: return true;
8987 case EXPR_BINARY_MUL_ASSIGN: return true;
8988 case EXPR_BINARY_DIV_ASSIGN: return true;
8989 case EXPR_BINARY_MOD_ASSIGN: return true;
8990 case EXPR_BINARY_ADD_ASSIGN: return true;
8991 case EXPR_BINARY_SUB_ASSIGN: return true;
8992 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8993 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8994 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8995 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8996 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8998 /* Only examine the right hand side of && and ||, because the left hand
8999 * side already has the effect of controlling the execution of the right
9001 case EXPR_BINARY_LOGICAL_AND:
9002 case EXPR_BINARY_LOGICAL_OR:
9003 /* Only examine the right hand side of a comma expression, because the left
9004 * hand side has a separate warning */
9005 case EXPR_BINARY_COMMA:
9006 return expression_has_effect(expr->binary.right);
9008 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9009 case EXPR_BINARY_ISGREATER: return false;
9010 case EXPR_BINARY_ISGREATEREQUAL: return false;
9011 case EXPR_BINARY_ISLESS: return false;
9012 case EXPR_BINARY_ISLESSEQUAL: return false;
9013 case EXPR_BINARY_ISLESSGREATER: return false;
9014 case EXPR_BINARY_ISUNORDERED: return false;
9017 internal_errorf(HERE, "unexpected expression");
9020 static void semantic_comma(binary_expression_t *expression)
9022 if (warning.unused_value) {
9023 const expression_t *const left = expression->left;
9024 if (!expression_has_effect(left)) {
9025 warningf(&left->base.source_position,
9026 "left-hand operand of comma expression has no effect");
9029 expression->base.type = expression->right->base.type;
9033 * @param prec_r precedence of the right operand
9035 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9036 static expression_t *parse_##binexpression_type(expression_t *left) \
9038 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9039 binexpr->binary.left = left; \
9042 expression_t *right = parse_sub_expression(prec_r); \
9044 binexpr->binary.right = right; \
9045 sfunc(&binexpr->binary); \
9050 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9051 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9052 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9053 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9054 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9055 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9056 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9057 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9058 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9059 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9060 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9061 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9062 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9063 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9064 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9065 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9066 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9067 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9068 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9069 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9070 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9071 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9072 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9073 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9074 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9075 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9076 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9077 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9078 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9079 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9082 static expression_t *parse_sub_expression(precedence_t precedence)
9084 if (token.type < 0) {
9085 return expected_expression_error();
9088 expression_parser_function_t *parser
9089 = &expression_parsers[token.type];
9090 source_position_t source_position = token.source_position;
9093 if (parser->parser != NULL) {
9094 left = parser->parser();
9096 left = parse_primary_expression();
9098 assert(left != NULL);
9099 left->base.source_position = source_position;
9102 if (token.type < 0) {
9103 return expected_expression_error();
9106 parser = &expression_parsers[token.type];
9107 if (parser->infix_parser == NULL)
9109 if (parser->infix_precedence < precedence)
9112 left = parser->infix_parser(left);
9114 assert(left != NULL);
9115 assert(left->kind != EXPR_UNKNOWN);
9116 left->base.source_position = source_position;
9123 * Parse an expression.
9125 static expression_t *parse_expression(void)
9127 return parse_sub_expression(PREC_EXPRESSION);
9131 * Register a parser for a prefix-like operator.
9133 * @param parser the parser function
9134 * @param token_type the token type of the prefix token
9136 static void register_expression_parser(parse_expression_function parser,
9139 expression_parser_function_t *entry = &expression_parsers[token_type];
9141 if (entry->parser != NULL) {
9142 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9143 panic("trying to register multiple expression parsers for a token");
9145 entry->parser = parser;
9149 * Register a parser for an infix operator with given precedence.
9151 * @param parser the parser function
9152 * @param token_type the token type of the infix operator
9153 * @param precedence the precedence of the operator
9155 static void register_infix_parser(parse_expression_infix_function parser,
9156 int token_type, unsigned precedence)
9158 expression_parser_function_t *entry = &expression_parsers[token_type];
9160 if (entry->infix_parser != NULL) {
9161 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9162 panic("trying to register multiple infix expression parsers for a "
9165 entry->infix_parser = parser;
9166 entry->infix_precedence = precedence;
9170 * Initialize the expression parsers.
9172 static void init_expression_parsers(void)
9174 memset(&expression_parsers, 0, sizeof(expression_parsers));
9176 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9177 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9178 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9179 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9180 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9181 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9182 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9183 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9184 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9185 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9186 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9187 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9188 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9189 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9190 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9191 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9192 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9193 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9194 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9195 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9196 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9197 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9198 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9199 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9200 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9201 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9202 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9203 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9204 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9205 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9206 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9207 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9208 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9209 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9210 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9211 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9212 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9214 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9215 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9216 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9217 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9218 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9219 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9220 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9221 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9222 register_expression_parser(parse_sizeof, T_sizeof);
9223 register_expression_parser(parse_alignof, T___alignof__);
9224 register_expression_parser(parse_extension, T___extension__);
9225 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9226 register_expression_parser(parse_delete, T_delete);
9227 register_expression_parser(parse_throw, T_throw);
9231 * Parse a asm statement arguments specification.
9233 static asm_argument_t *parse_asm_arguments(bool is_out)
9235 asm_argument_t *result = NULL;
9236 asm_argument_t **anchor = &result;
9238 while (token.type == T_STRING_LITERAL || token.type == '[') {
9239 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9240 memset(argument, 0, sizeof(argument[0]));
9242 if (token.type == '[') {
9244 if (token.type != T_IDENTIFIER) {
9245 parse_error_expected("while parsing asm argument",
9246 T_IDENTIFIER, NULL);
9249 argument->symbol = token.v.symbol;
9254 argument->constraints = parse_string_literals();
9256 add_anchor_token(')');
9257 expression_t *expression = parse_expression();
9258 rem_anchor_token(')');
9260 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9261 * change size or type representation (e.g. int -> long is ok, but
9262 * int -> float is not) */
9263 if (expression->kind == EXPR_UNARY_CAST) {
9264 type_t *const type = expression->base.type;
9265 type_kind_t const kind = type->kind;
9266 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9269 if (kind == TYPE_ATOMIC) {
9270 atomic_type_kind_t const akind = type->atomic.akind;
9271 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9272 size = get_atomic_type_size(akind);
9274 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9275 size = get_atomic_type_size(get_intptr_kind());
9279 expression_t *const value = expression->unary.value;
9280 type_t *const value_type = value->base.type;
9281 type_kind_t const value_kind = value_type->kind;
9283 unsigned value_flags;
9284 unsigned value_size;
9285 if (value_kind == TYPE_ATOMIC) {
9286 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9287 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9288 value_size = get_atomic_type_size(value_akind);
9289 } else if (value_kind == TYPE_POINTER) {
9290 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9291 value_size = get_atomic_type_size(get_intptr_kind());
9296 if (value_flags != flags || value_size != size)
9300 } while (expression->kind == EXPR_UNARY_CAST);
9304 if (!is_lvalue(expression)) {
9305 errorf(&expression->base.source_position,
9306 "asm output argument is not an lvalue");
9309 if (argument->constraints.begin[0] == '+')
9310 mark_vars_read(expression, NULL);
9312 mark_vars_read(expression, NULL);
9314 argument->expression = expression;
9317 set_address_taken(expression, true);
9320 anchor = &argument->next;
9322 if (token.type != ',')
9333 * Parse a asm statement clobber specification.
9335 static asm_clobber_t *parse_asm_clobbers(void)
9337 asm_clobber_t *result = NULL;
9338 asm_clobber_t *last = NULL;
9340 while (token.type == T_STRING_LITERAL) {
9341 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9342 clobber->clobber = parse_string_literals();
9345 last->next = clobber;
9351 if (token.type != ',')
9360 * Parse an asm statement.
9362 static statement_t *parse_asm_statement(void)
9364 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9365 asm_statement_t *asm_statement = &statement->asms;
9369 if (token.type == T_volatile) {
9371 asm_statement->is_volatile = true;
9375 add_anchor_token(')');
9376 add_anchor_token(':');
9377 asm_statement->asm_text = parse_string_literals();
9379 if (token.type != ':') {
9380 rem_anchor_token(':');
9385 asm_statement->outputs = parse_asm_arguments(true);
9386 if (token.type != ':') {
9387 rem_anchor_token(':');
9392 asm_statement->inputs = parse_asm_arguments(false);
9393 if (token.type != ':') {
9394 rem_anchor_token(':');
9397 rem_anchor_token(':');
9400 asm_statement->clobbers = parse_asm_clobbers();
9403 rem_anchor_token(')');
9407 if (asm_statement->outputs == NULL) {
9408 /* GCC: An 'asm' instruction without any output operands will be treated
9409 * identically to a volatile 'asm' instruction. */
9410 asm_statement->is_volatile = true;
9415 return create_invalid_statement();
9419 * Parse a case statement.
9421 static statement_t *parse_case_statement(void)
9423 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9424 source_position_t *const pos = &statement->base.source_position;
9428 expression_t *const expression = parse_expression();
9429 statement->case_label.expression = expression;
9430 if (!is_constant_expression(expression)) {
9431 /* This check does not prevent the error message in all cases of an
9432 * prior error while parsing the expression. At least it catches the
9433 * common case of a mistyped enum entry. */
9434 if (is_type_valid(skip_typeref(expression->base.type))) {
9435 errorf(pos, "case label does not reduce to an integer constant");
9437 statement->case_label.is_bad = true;
9439 long const val = fold_constant(expression);
9440 statement->case_label.first_case = val;
9441 statement->case_label.last_case = val;
9445 if (token.type == T_DOTDOTDOT) {
9447 expression_t *const end_range = parse_expression();
9448 statement->case_label.end_range = end_range;
9449 if (!is_constant_expression(end_range)) {
9450 /* This check does not prevent the error message in all cases of an
9451 * prior error while parsing the expression. At least it catches the
9452 * common case of a mistyped enum entry. */
9453 if (is_type_valid(skip_typeref(end_range->base.type))) {
9454 errorf(pos, "case range does not reduce to an integer constant");
9456 statement->case_label.is_bad = true;
9458 long const val = fold_constant(end_range);
9459 statement->case_label.last_case = val;
9461 if (warning.other && val < statement->case_label.first_case) {
9462 statement->case_label.is_empty_range = true;
9463 warningf(pos, "empty range specified");
9469 PUSH_PARENT(statement);
9473 if (current_switch != NULL) {
9474 if (! statement->case_label.is_bad) {
9475 /* Check for duplicate case values */
9476 case_label_statement_t *c = &statement->case_label;
9477 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9478 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9481 if (c->last_case < l->first_case || c->first_case > l->last_case)
9484 errorf(pos, "duplicate case value (previously used %P)",
9485 &l->base.source_position);
9489 /* link all cases into the switch statement */
9490 if (current_switch->last_case == NULL) {
9491 current_switch->first_case = &statement->case_label;
9493 current_switch->last_case->next = &statement->case_label;
9495 current_switch->last_case = &statement->case_label;
9497 errorf(pos, "case label not within a switch statement");
9500 statement_t *const inner_stmt = parse_statement();
9501 statement->case_label.statement = inner_stmt;
9502 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9503 errorf(&inner_stmt->base.source_position, "declaration after case label");
9510 return create_invalid_statement();
9514 * Parse a default statement.
9516 static statement_t *parse_default_statement(void)
9518 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9522 PUSH_PARENT(statement);
9525 if (current_switch != NULL) {
9526 const case_label_statement_t *def_label = current_switch->default_label;
9527 if (def_label != NULL) {
9528 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9529 &def_label->base.source_position);
9531 current_switch->default_label = &statement->case_label;
9533 /* link all cases into the switch statement */
9534 if (current_switch->last_case == NULL) {
9535 current_switch->first_case = &statement->case_label;
9537 current_switch->last_case->next = &statement->case_label;
9539 current_switch->last_case = &statement->case_label;
9542 errorf(&statement->base.source_position,
9543 "'default' label not within a switch statement");
9546 statement_t *const inner_stmt = parse_statement();
9547 statement->case_label.statement = inner_stmt;
9548 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9549 errorf(&inner_stmt->base.source_position, "declaration after default label");
9556 return create_invalid_statement();
9560 * Parse a label statement.
9562 static statement_t *parse_label_statement(void)
9564 assert(token.type == T_IDENTIFIER);
9565 symbol_t *symbol = token.v.symbol;
9566 label_t *label = get_label(symbol);
9568 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9569 statement->label.label = label;
9573 PUSH_PARENT(statement);
9575 /* if statement is already set then the label is defined twice,
9576 * otherwise it was just mentioned in a goto/local label declaration so far
9578 if (label->statement != NULL) {
9579 errorf(HERE, "duplicate label '%Y' (declared %P)",
9580 symbol, &label->base.source_position);
9582 label->base.source_position = token.source_position;
9583 label->statement = statement;
9588 if (token.type == '}') {
9589 /* TODO only warn? */
9590 if (warning.other && false) {
9591 warningf(HERE, "label at end of compound statement");
9592 statement->label.statement = create_empty_statement();
9594 errorf(HERE, "label at end of compound statement");
9595 statement->label.statement = create_invalid_statement();
9597 } else if (token.type == ';') {
9598 /* Eat an empty statement here, to avoid the warning about an empty
9599 * statement after a label. label:; is commonly used to have a label
9600 * before a closing brace. */
9601 statement->label.statement = create_empty_statement();
9604 statement_t *const inner_stmt = parse_statement();
9605 statement->label.statement = inner_stmt;
9606 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9607 errorf(&inner_stmt->base.source_position, "declaration after label");
9611 /* remember the labels in a list for later checking */
9612 *label_anchor = &statement->label;
9613 label_anchor = &statement->label.next;
9620 * Parse an if statement.
9622 static statement_t *parse_if(void)
9624 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9628 PUSH_PARENT(statement);
9630 add_anchor_token('{');
9633 add_anchor_token(')');
9634 expression_t *const expr = parse_expression();
9635 statement->ifs.condition = expr;
9636 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9638 semantic_condition(expr, "condition of 'if'-statment");
9639 mark_vars_read(expr, NULL);
9640 rem_anchor_token(')');
9644 rem_anchor_token('{');
9646 add_anchor_token(T_else);
9647 statement->ifs.true_statement = parse_statement();
9648 rem_anchor_token(T_else);
9650 if (token.type == T_else) {
9652 statement->ifs.false_statement = parse_statement();
9660 * Check that all enums are handled in a switch.
9662 * @param statement the switch statement to check
9664 static void check_enum_cases(const switch_statement_t *statement) {
9665 const type_t *type = skip_typeref(statement->expression->base.type);
9666 if (! is_type_enum(type))
9668 const enum_type_t *enumt = &type->enumt;
9670 /* if we have a default, no warnings */
9671 if (statement->default_label != NULL)
9674 /* FIXME: calculation of value should be done while parsing */
9675 /* TODO: quadratic algorithm here. Change to an n log n one */
9676 long last_value = -1;
9677 const entity_t *entry = enumt->enume->base.next;
9678 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9679 entry = entry->base.next) {
9680 const expression_t *expression = entry->enum_value.value;
9681 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9683 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9684 if (l->expression == NULL)
9686 if (l->first_case <= value && value <= l->last_case) {
9692 warningf(&statement->base.source_position,
9693 "enumeration value '%Y' not handled in switch",
9694 entry->base.symbol);
9701 * Parse a switch statement.
9703 static statement_t *parse_switch(void)
9705 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9709 PUSH_PARENT(statement);
9712 add_anchor_token(')');
9713 expression_t *const expr = parse_expression();
9714 mark_vars_read(expr, NULL);
9715 type_t * type = skip_typeref(expr->base.type);
9716 if (is_type_integer(type)) {
9717 type = promote_integer(type);
9718 if (warning.traditional) {
9719 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9720 warningf(&expr->base.source_position,
9721 "'%T' switch expression not converted to '%T' in ISO C",
9725 } else if (is_type_valid(type)) {
9726 errorf(&expr->base.source_position,
9727 "switch quantity is not an integer, but '%T'", type);
9728 type = type_error_type;
9730 statement->switchs.expression = create_implicit_cast(expr, type);
9732 rem_anchor_token(')');
9734 switch_statement_t *rem = current_switch;
9735 current_switch = &statement->switchs;
9736 statement->switchs.body = parse_statement();
9737 current_switch = rem;
9739 if (warning.switch_default &&
9740 statement->switchs.default_label == NULL) {
9741 warningf(&statement->base.source_position, "switch has no default case");
9743 if (warning.switch_enum)
9744 check_enum_cases(&statement->switchs);
9750 return create_invalid_statement();
9753 static statement_t *parse_loop_body(statement_t *const loop)
9755 statement_t *const rem = current_loop;
9756 current_loop = loop;
9758 statement_t *const body = parse_statement();
9765 * Parse a while statement.
9767 static statement_t *parse_while(void)
9769 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9773 PUSH_PARENT(statement);
9776 add_anchor_token(')');
9777 expression_t *const cond = parse_expression();
9778 statement->whiles.condition = cond;
9779 /* §6.8.5:2 The controlling expression of an iteration statement shall
9780 * have scalar type. */
9781 semantic_condition(cond, "condition of 'while'-statement");
9782 mark_vars_read(cond, NULL);
9783 rem_anchor_token(')');
9786 statement->whiles.body = parse_loop_body(statement);
9792 return create_invalid_statement();
9796 * Parse a do statement.
9798 static statement_t *parse_do(void)
9800 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9804 PUSH_PARENT(statement);
9806 add_anchor_token(T_while);
9807 statement->do_while.body = parse_loop_body(statement);
9808 rem_anchor_token(T_while);
9812 add_anchor_token(')');
9813 expression_t *const cond = parse_expression();
9814 statement->do_while.condition = cond;
9815 /* §6.8.5:2 The controlling expression of an iteration statement shall
9816 * have scalar type. */
9817 semantic_condition(cond, "condition of 'do-while'-statement");
9818 mark_vars_read(cond, NULL);
9819 rem_anchor_token(')');
9827 return create_invalid_statement();
9831 * Parse a for statement.
9833 static statement_t *parse_for(void)
9835 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9839 PUSH_PARENT(statement);
9841 size_t const top = environment_top();
9842 scope_push(&statement->fors.scope);
9845 add_anchor_token(')');
9847 if (token.type == ';') {
9849 } else if (is_declaration_specifier(&token, false)) {
9850 parse_declaration(record_entity);
9852 add_anchor_token(';');
9853 expression_t *const init = parse_expression();
9854 statement->fors.initialisation = init;
9855 mark_vars_read(init, VAR_ANY);
9856 if (warning.unused_value && !expression_has_effect(init)) {
9857 warningf(&init->base.source_position,
9858 "initialisation of 'for'-statement has no effect");
9860 rem_anchor_token(';');
9864 if (token.type != ';') {
9865 add_anchor_token(';');
9866 expression_t *const cond = parse_expression();
9867 statement->fors.condition = cond;
9868 /* §6.8.5:2 The controlling expression of an iteration statement shall
9869 * have scalar type. */
9870 semantic_condition(cond, "condition of 'for'-statement");
9871 mark_vars_read(cond, NULL);
9872 rem_anchor_token(';');
9875 if (token.type != ')') {
9876 expression_t *const step = parse_expression();
9877 statement->fors.step = step;
9878 mark_vars_read(step, VAR_ANY);
9879 if (warning.unused_value && !expression_has_effect(step)) {
9880 warningf(&step->base.source_position,
9881 "step of 'for'-statement has no effect");
9885 rem_anchor_token(')');
9886 statement->fors.body = parse_loop_body(statement);
9888 assert(current_scope == &statement->fors.scope);
9890 environment_pop_to(top);
9897 rem_anchor_token(')');
9898 assert(current_scope == &statement->fors.scope);
9900 environment_pop_to(top);
9902 return create_invalid_statement();
9906 * Parse a goto statement.
9908 static statement_t *parse_goto(void)
9910 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9913 if (GNU_MODE && token.type == '*') {
9915 expression_t *expression = parse_expression();
9916 mark_vars_read(expression, NULL);
9918 /* Argh: although documentation says the expression must be of type void*,
9919 * gcc accepts anything that can be casted into void* without error */
9920 type_t *type = expression->base.type;
9922 if (type != type_error_type) {
9923 if (!is_type_pointer(type) && !is_type_integer(type)) {
9924 errorf(&expression->base.source_position,
9925 "cannot convert to a pointer type");
9926 } else if (warning.other && type != type_void_ptr) {
9927 warningf(&expression->base.source_position,
9928 "type of computed goto expression should be 'void*' not '%T'", type);
9930 expression = create_implicit_cast(expression, type_void_ptr);
9933 statement->gotos.expression = expression;
9935 if (token.type != T_IDENTIFIER) {
9937 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9939 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9943 symbol_t *symbol = token.v.symbol;
9946 statement->gotos.label = get_label(symbol);
9949 /* remember the goto's in a list for later checking */
9950 *goto_anchor = &statement->gotos;
9951 goto_anchor = &statement->gotos.next;
9957 return create_invalid_statement();
9961 * Parse a continue statement.
9963 static statement_t *parse_continue(void)
9965 if (current_loop == NULL) {
9966 errorf(HERE, "continue statement not within loop");
9969 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9979 * Parse a break statement.
9981 static statement_t *parse_break(void)
9983 if (current_switch == NULL && current_loop == NULL) {
9984 errorf(HERE, "break statement not within loop or switch");
9987 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9997 * Parse a __leave statement.
9999 static statement_t *parse_leave_statement(void)
10001 if (current_try == NULL) {
10002 errorf(HERE, "__leave statement not within __try");
10005 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10015 * Check if a given entity represents a local variable.
10017 static bool is_local_variable(const entity_t *entity)
10019 if (entity->kind != ENTITY_VARIABLE)
10022 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10023 case STORAGE_CLASS_AUTO:
10024 case STORAGE_CLASS_REGISTER: {
10025 const type_t *type = skip_typeref(entity->declaration.type);
10026 if (is_type_function(type)) {
10038 * Check if a given expression represents a local variable.
10040 static bool expression_is_local_variable(const expression_t *expression)
10042 if (expression->base.kind != EXPR_REFERENCE) {
10045 const entity_t *entity = expression->reference.entity;
10046 return is_local_variable(entity);
10050 * Check if a given expression represents a local variable and
10051 * return its declaration then, else return NULL.
10053 entity_t *expression_is_variable(const expression_t *expression)
10055 if (expression->base.kind != EXPR_REFERENCE) {
10058 entity_t *entity = expression->reference.entity;
10059 if (entity->kind != ENTITY_VARIABLE)
10066 * Parse a return statement.
10068 static statement_t *parse_return(void)
10072 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10074 expression_t *return_value = NULL;
10075 if (token.type != ';') {
10076 return_value = parse_expression();
10077 mark_vars_read(return_value, NULL);
10080 const type_t *const func_type = skip_typeref(current_function->base.type);
10081 assert(is_type_function(func_type));
10082 type_t *const return_type = skip_typeref(func_type->function.return_type);
10084 if (return_value != NULL) {
10085 type_t *return_value_type = skip_typeref(return_value->base.type);
10087 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10088 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10089 if (warning.other) {
10090 warningf(&statement->base.source_position,
10091 "'return' with a value, in function returning void");
10093 return_value = NULL;
10095 assign_error_t error = semantic_assign(return_type, return_value);
10096 report_assign_error(error, return_type, return_value, "'return'",
10097 &statement->base.source_position);
10098 return_value = create_implicit_cast(return_value, return_type);
10100 /* check for returning address of a local var */
10101 if (warning.other && return_value != NULL
10102 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10103 const expression_t *expression = return_value->unary.value;
10104 if (expression_is_local_variable(expression)) {
10105 warningf(&statement->base.source_position,
10106 "function returns address of local variable");
10109 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10110 warningf(&statement->base.source_position,
10111 "'return' without value, in function returning non-void");
10113 statement->returns.value = return_value;
10122 * Parse a declaration statement.
10124 static statement_t *parse_declaration_statement(void)
10126 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10128 entity_t *before = current_scope->last_entity;
10130 parse_external_declaration();
10132 parse_declaration(record_entity);
10134 if (before == NULL) {
10135 statement->declaration.declarations_begin = current_scope->entities;
10137 statement->declaration.declarations_begin = before->base.next;
10139 statement->declaration.declarations_end = current_scope->last_entity;
10145 * Parse an expression statement, ie. expr ';'.
10147 static statement_t *parse_expression_statement(void)
10149 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10151 expression_t *const expr = parse_expression();
10152 statement->expression.expression = expr;
10153 mark_vars_read(expr, VAR_ANY);
10162 * Parse a microsoft __try { } __finally { } or
10163 * __try{ } __except() { }
10165 static statement_t *parse_ms_try_statment(void)
10167 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10170 PUSH_PARENT(statement);
10172 ms_try_statement_t *rem = current_try;
10173 current_try = &statement->ms_try;
10174 statement->ms_try.try_statement = parse_compound_statement(false);
10179 if (token.type == T___except) {
10182 add_anchor_token(')');
10183 expression_t *const expr = parse_expression();
10184 mark_vars_read(expr, NULL);
10185 type_t * type = skip_typeref(expr->base.type);
10186 if (is_type_integer(type)) {
10187 type = promote_integer(type);
10188 } else if (is_type_valid(type)) {
10189 errorf(&expr->base.source_position,
10190 "__expect expression is not an integer, but '%T'", type);
10191 type = type_error_type;
10193 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10194 rem_anchor_token(')');
10196 statement->ms_try.final_statement = parse_compound_statement(false);
10197 } else if (token.type == T__finally) {
10199 statement->ms_try.final_statement = parse_compound_statement(false);
10201 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10202 return create_invalid_statement();
10206 return create_invalid_statement();
10209 static statement_t *parse_empty_statement(void)
10211 if (warning.empty_statement) {
10212 warningf(HERE, "statement is empty");
10214 statement_t *const statement = create_empty_statement();
10219 static statement_t *parse_local_label_declaration(void)
10221 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10225 entity_t *begin = NULL, *end = NULL;
10228 if (token.type != T_IDENTIFIER) {
10229 parse_error_expected("while parsing local label declaration",
10230 T_IDENTIFIER, NULL);
10233 symbol_t *symbol = token.v.symbol;
10234 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10235 if (entity != NULL && entity->base.parent_scope == current_scope) {
10236 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10237 symbol, &entity->base.source_position);
10239 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10241 entity->base.parent_scope = current_scope;
10242 entity->base.namespc = NAMESPACE_LABEL;
10243 entity->base.source_position = token.source_position;
10244 entity->base.symbol = symbol;
10247 end->base.next = entity;
10252 environment_push(entity);
10256 if (token.type != ',')
10262 statement->declaration.declarations_begin = begin;
10263 statement->declaration.declarations_end = end;
10267 static void parse_namespace_definition(void)
10271 entity_t *entity = NULL;
10272 symbol_t *symbol = NULL;
10274 if (token.type == T_IDENTIFIER) {
10275 symbol = token.v.symbol;
10278 entity = get_entity(symbol, NAMESPACE_NORMAL);
10279 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10280 && entity->base.parent_scope == current_scope) {
10281 error_redefined_as_different_kind(&token.source_position,
10282 entity, ENTITY_NAMESPACE);
10287 if (entity == NULL) {
10288 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10289 entity->base.symbol = symbol;
10290 entity->base.source_position = token.source_position;
10291 entity->base.namespc = NAMESPACE_NORMAL;
10292 entity->base.parent_scope = current_scope;
10295 if (token.type == '=') {
10296 /* TODO: parse namespace alias */
10297 panic("namespace alias definition not supported yet");
10300 environment_push(entity);
10301 append_entity(current_scope, entity);
10303 size_t const top = environment_top();
10304 scope_push(&entity->namespacee.members);
10311 assert(current_scope == &entity->namespacee.members);
10313 environment_pop_to(top);
10317 * Parse a statement.
10318 * There's also parse_statement() which additionally checks for
10319 * "statement has no effect" warnings
10321 static statement_t *intern_parse_statement(void)
10323 statement_t *statement = NULL;
10325 /* declaration or statement */
10326 add_anchor_token(';');
10327 switch (token.type) {
10328 case T_IDENTIFIER: {
10329 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10330 if (la1_type == ':') {
10331 statement = parse_label_statement();
10332 } else if (is_typedef_symbol(token.v.symbol)) {
10333 statement = parse_declaration_statement();
10335 /* it's an identifier, the grammar says this must be an
10336 * expression statement. However it is common that users mistype
10337 * declaration types, so we guess a bit here to improve robustness
10338 * for incorrect programs */
10339 switch (la1_type) {
10342 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10343 goto expression_statment;
10348 statement = parse_declaration_statement();
10352 expression_statment:
10353 statement = parse_expression_statement();
10360 case T___extension__:
10361 /* This can be a prefix to a declaration or an expression statement.
10362 * We simply eat it now and parse the rest with tail recursion. */
10365 } while (token.type == T___extension__);
10366 bool old_gcc_extension = in_gcc_extension;
10367 in_gcc_extension = true;
10368 statement = parse_statement();
10369 in_gcc_extension = old_gcc_extension;
10373 statement = parse_declaration_statement();
10377 statement = parse_local_label_declaration();
10380 case ';': statement = parse_empty_statement(); break;
10381 case '{': statement = parse_compound_statement(false); break;
10382 case T___leave: statement = parse_leave_statement(); break;
10383 case T___try: statement = parse_ms_try_statment(); break;
10384 case T_asm: statement = parse_asm_statement(); break;
10385 case T_break: statement = parse_break(); break;
10386 case T_case: statement = parse_case_statement(); break;
10387 case T_continue: statement = parse_continue(); break;
10388 case T_default: statement = parse_default_statement(); break;
10389 case T_do: statement = parse_do(); break;
10390 case T_for: statement = parse_for(); break;
10391 case T_goto: statement = parse_goto(); break;
10392 case T_if: statement = parse_if(); break;
10393 case T_return: statement = parse_return(); break;
10394 case T_switch: statement = parse_switch(); break;
10395 case T_while: statement = parse_while(); break;
10398 statement = parse_expression_statement();
10402 errorf(HERE, "unexpected token %K while parsing statement", &token);
10403 statement = create_invalid_statement();
10408 rem_anchor_token(';');
10410 assert(statement != NULL
10411 && statement->base.source_position.input_name != NULL);
10417 * parse a statement and emits "statement has no effect" warning if needed
10418 * (This is really a wrapper around intern_parse_statement with check for 1
10419 * single warning. It is needed, because for statement expressions we have
10420 * to avoid the warning on the last statement)
10422 static statement_t *parse_statement(void)
10424 statement_t *statement = intern_parse_statement();
10426 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10427 expression_t *expression = statement->expression.expression;
10428 if (!expression_has_effect(expression)) {
10429 warningf(&expression->base.source_position,
10430 "statement has no effect");
10438 * Parse a compound statement.
10440 static statement_t *parse_compound_statement(bool inside_expression_statement)
10442 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10444 PUSH_PARENT(statement);
10447 add_anchor_token('}');
10449 size_t const top = environment_top();
10450 scope_push(&statement->compound.scope);
10452 statement_t **anchor = &statement->compound.statements;
10453 bool only_decls_so_far = true;
10454 while (token.type != '}') {
10455 if (token.type == T_EOF) {
10456 errorf(&statement->base.source_position,
10457 "EOF while parsing compound statement");
10460 statement_t *sub_statement = intern_parse_statement();
10461 if (is_invalid_statement(sub_statement)) {
10462 /* an error occurred. if we are at an anchor, return */
10468 if (warning.declaration_after_statement) {
10469 if (sub_statement->kind != STATEMENT_DECLARATION) {
10470 only_decls_so_far = false;
10471 } else if (!only_decls_so_far) {
10472 warningf(&sub_statement->base.source_position,
10473 "ISO C90 forbids mixed declarations and code");
10477 *anchor = sub_statement;
10479 while (sub_statement->base.next != NULL)
10480 sub_statement = sub_statement->base.next;
10482 anchor = &sub_statement->base.next;
10486 /* look over all statements again to produce no effect warnings */
10487 if (warning.unused_value) {
10488 statement_t *sub_statement = statement->compound.statements;
10489 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10490 if (sub_statement->kind != STATEMENT_EXPRESSION)
10492 /* don't emit a warning for the last expression in an expression
10493 * statement as it has always an effect */
10494 if (inside_expression_statement && sub_statement->base.next == NULL)
10497 expression_t *expression = sub_statement->expression.expression;
10498 if (!expression_has_effect(expression)) {
10499 warningf(&expression->base.source_position,
10500 "statement has no effect");
10506 rem_anchor_token('}');
10507 assert(current_scope == &statement->compound.scope);
10509 environment_pop_to(top);
10516 * Check for unused global static functions and variables
10518 static void check_unused_globals(void)
10520 if (!warning.unused_function && !warning.unused_variable)
10523 for (const entity_t *entity = file_scope->entities; entity != NULL;
10524 entity = entity->base.next) {
10525 if (!is_declaration(entity))
10528 const declaration_t *declaration = &entity->declaration;
10529 if (declaration->used ||
10530 declaration->modifiers & DM_UNUSED ||
10531 declaration->modifiers & DM_USED ||
10532 declaration->storage_class != STORAGE_CLASS_STATIC)
10535 type_t *const type = declaration->type;
10537 if (entity->kind == ENTITY_FUNCTION) {
10538 /* inhibit warning for static inline functions */
10539 if (entity->function.is_inline)
10542 s = entity->function.statement != NULL ? "defined" : "declared";
10547 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10548 type, declaration->base.symbol, s);
10552 static void parse_global_asm(void)
10554 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10559 statement->asms.asm_text = parse_string_literals();
10560 statement->base.next = unit->global_asm;
10561 unit->global_asm = statement;
10569 static void parse_linkage_specification(void)
10572 assert(token.type == T_STRING_LITERAL);
10574 const char *linkage = parse_string_literals().begin;
10576 linkage_kind_t old_linkage = current_linkage;
10577 linkage_kind_t new_linkage;
10578 if (strcmp(linkage, "C") == 0) {
10579 new_linkage = LINKAGE_C;
10580 } else if (strcmp(linkage, "C++") == 0) {
10581 new_linkage = LINKAGE_CXX;
10583 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10584 new_linkage = LINKAGE_INVALID;
10586 current_linkage = new_linkage;
10588 if (token.type == '{') {
10597 assert(current_linkage == new_linkage);
10598 current_linkage = old_linkage;
10601 static void parse_external(void)
10603 switch (token.type) {
10604 DECLARATION_START_NO_EXTERN
10606 case T___extension__:
10607 case '(': /* for function declarations with implicit return type and
10608 * parenthesized declarator, i.e. (f)(void); */
10609 parse_external_declaration();
10613 if (look_ahead(1)->type == T_STRING_LITERAL) {
10614 parse_linkage_specification();
10616 parse_external_declaration();
10621 parse_global_asm();
10625 parse_namespace_definition();
10629 if (!strict_mode) {
10631 warningf(HERE, "stray ';' outside of function");
10638 errorf(HERE, "stray %K outside of function", &token);
10639 if (token.type == '(' || token.type == '{' || token.type == '[')
10640 eat_until_matching_token(token.type);
10646 static void parse_externals(void)
10648 add_anchor_token('}');
10649 add_anchor_token(T_EOF);
10652 unsigned char token_anchor_copy[T_LAST_TOKEN];
10653 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10656 while (token.type != T_EOF && token.type != '}') {
10658 bool anchor_leak = false;
10659 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10660 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10662 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10663 anchor_leak = true;
10666 if (in_gcc_extension) {
10667 errorf(HERE, "Leaked __extension__");
10668 anchor_leak = true;
10678 rem_anchor_token(T_EOF);
10679 rem_anchor_token('}');
10683 * Parse a translation unit.
10685 static void parse_translation_unit(void)
10687 add_anchor_token(T_EOF);
10692 if (token.type == T_EOF)
10695 errorf(HERE, "stray %K outside of function", &token);
10696 if (token.type == '(' || token.type == '{' || token.type == '[')
10697 eat_until_matching_token(token.type);
10705 * @return the translation unit or NULL if errors occurred.
10707 void start_parsing(void)
10709 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10710 label_stack = NEW_ARR_F(stack_entry_t, 0);
10711 diagnostic_count = 0;
10715 type_set_output(stderr);
10716 ast_set_output(stderr);
10718 assert(unit == NULL);
10719 unit = allocate_ast_zero(sizeof(unit[0]));
10721 assert(file_scope == NULL);
10722 file_scope = &unit->scope;
10724 assert(current_scope == NULL);
10725 scope_push(&unit->scope);
10728 translation_unit_t *finish_parsing(void)
10730 /* do NOT use scope_pop() here, this will crash, will it by hand */
10731 assert(current_scope == &unit->scope);
10732 current_scope = NULL;
10734 assert(file_scope == &unit->scope);
10735 check_unused_globals();
10738 DEL_ARR_F(environment_stack);
10739 DEL_ARR_F(label_stack);
10741 translation_unit_t *result = unit;
10748 lookahead_bufpos = 0;
10749 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10752 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10753 parse_translation_unit();
10757 * Initialize the parser.
10759 void init_parser(void)
10761 sym_anonymous = symbol_table_insert("<anonymous>");
10763 if (c_mode & _MS) {
10764 /* add predefined symbols for extended-decl-modifier */
10765 sym_align = symbol_table_insert("align");
10766 sym_allocate = symbol_table_insert("allocate");
10767 sym_dllimport = symbol_table_insert("dllimport");
10768 sym_dllexport = symbol_table_insert("dllexport");
10769 sym_naked = symbol_table_insert("naked");
10770 sym_noinline = symbol_table_insert("noinline");
10771 sym_noreturn = symbol_table_insert("noreturn");
10772 sym_nothrow = symbol_table_insert("nothrow");
10773 sym_novtable = symbol_table_insert("novtable");
10774 sym_property = symbol_table_insert("property");
10775 sym_get = symbol_table_insert("get");
10776 sym_put = symbol_table_insert("put");
10777 sym_selectany = symbol_table_insert("selectany");
10778 sym_thread = symbol_table_insert("thread");
10779 sym_uuid = symbol_table_insert("uuid");
10780 sym_deprecated = symbol_table_insert("deprecated");
10781 sym_restrict = symbol_table_insert("restrict");
10782 sym_noalias = symbol_table_insert("noalias");
10784 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10786 init_expression_parsers();
10787 obstack_init(&temp_obst);
10789 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10790 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10794 * Terminate the parser.
10796 void exit_parser(void)
10798 obstack_free(&temp_obst, NULL);