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;
4029 /* §6.9.1:6 The declarations in the declaration list shall contain no
4030 * storage-class specifier other than register and no
4031 * initializations. */
4032 switch (declaration->declared_storage_class) {
4033 /* Allowed storage classes */
4034 case STORAGE_CLASS_NONE:
4035 case STORAGE_CLASS_REGISTER:
4039 errorf(pos, "parameter may only have none or register storage class");
4043 type_t *const orig_type = declaration->type;
4044 /* §6.7.5.3:7 A declaration of a parameter as ``array of type'' shall be
4045 * adjusted to ``qualified pointer to type'', [...]
4046 * §6.7.5.3:8 A declaration of a parameter as ``function returning type''
4047 * shall be adjusted to ``pointer to function returning type'',
4050 type_t *const type = automatic_type_conversion(orig_type);
4051 declaration->type = type;
4053 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type list in
4054 * a function declarator that is part of a definition of that
4055 * function shall not have incomplete type. */
4056 if (is_type_incomplete(skip_typeref(type))) {
4057 errorf(pos, "parameter '%#T' has incomplete type",
4058 orig_type, declaration->base.symbol);
4062 static entity_t *parse_parameter(void)
4064 declaration_specifiers_t specifiers;
4065 memset(&specifiers, 0, sizeof(specifiers));
4067 parse_declaration_specifiers(&specifiers);
4069 entity_t *entity = parse_declarator(&specifiers, true, false);
4070 anonymous_entity = NULL;
4075 * Parses function type parameters (and optionally creates variable_t entities
4076 * for them in a scope)
4078 static void parse_parameters(function_type_t *type, scope_t *scope)
4081 add_anchor_token(')');
4082 int saved_comma_state = save_and_reset_anchor_state(',');
4084 if (token.type == T_IDENTIFIER &&
4085 !is_typedef_symbol(token.v.symbol)) {
4086 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4087 if (la1_type == ',' || la1_type == ')') {
4088 type->kr_style_parameters = true;
4089 parse_identifier_list(scope);
4090 goto parameters_finished;
4094 if (token.type == ')') {
4095 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4096 if (!(c_mode & _CXX))
4097 type->unspecified_parameters = true;
4098 goto parameters_finished;
4101 function_parameter_t *parameter;
4102 function_parameter_t *last_parameter = NULL;
4105 switch (token.type) {
4108 type->variadic = true;
4109 goto parameters_finished;
4112 case T___extension__:
4115 entity_t *entity = parse_parameter();
4116 if (entity->kind == ENTITY_TYPEDEF) {
4117 errorf(&entity->base.source_position,
4118 "typedef not allowed as function parameter");
4121 assert(is_declaration(entity));
4123 /* func(void) is not a parameter */
4124 if (last_parameter == NULL
4125 && token.type == ')'
4126 && entity->base.symbol == NULL
4127 && skip_typeref(entity->declaration.type) == type_void) {
4128 goto parameters_finished;
4130 semantic_parameter(&entity->declaration);
4132 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4133 memset(parameter, 0, sizeof(parameter[0]));
4134 parameter->type = entity->declaration.type;
4136 if (scope != NULL) {
4137 append_entity(scope, entity);
4140 if (last_parameter != NULL) {
4141 last_parameter->next = parameter;
4143 type->parameters = parameter;
4145 last_parameter = parameter;
4150 goto parameters_finished;
4152 if (token.type != ',') {
4153 goto parameters_finished;
4159 parameters_finished:
4160 rem_anchor_token(')');
4164 restore_anchor_state(',', saved_comma_state);
4167 typedef enum construct_type_kind_t {
4170 CONSTRUCT_REFERENCE,
4173 } construct_type_kind_t;
4175 typedef struct construct_type_t construct_type_t;
4176 struct construct_type_t {
4177 construct_type_kind_t kind;
4178 construct_type_t *next;
4181 typedef struct parsed_pointer_t parsed_pointer_t;
4182 struct parsed_pointer_t {
4183 construct_type_t construct_type;
4184 type_qualifiers_t type_qualifiers;
4185 variable_t *base_variable; /**< MS __based extension. */
4188 typedef struct parsed_reference_t parsed_reference_t;
4189 struct parsed_reference_t {
4190 construct_type_t construct_type;
4193 typedef struct construct_function_type_t construct_function_type_t;
4194 struct construct_function_type_t {
4195 construct_type_t construct_type;
4196 type_t *function_type;
4199 typedef struct parsed_array_t parsed_array_t;
4200 struct parsed_array_t {
4201 construct_type_t construct_type;
4202 type_qualifiers_t type_qualifiers;
4208 typedef struct construct_base_type_t construct_base_type_t;
4209 struct construct_base_type_t {
4210 construct_type_t construct_type;
4214 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4218 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4219 memset(pointer, 0, sizeof(pointer[0]));
4220 pointer->construct_type.kind = CONSTRUCT_POINTER;
4221 pointer->type_qualifiers = parse_type_qualifiers();
4222 pointer->base_variable = base_variable;
4224 return &pointer->construct_type;
4227 static construct_type_t *parse_reference_declarator(void)
4231 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4232 memset(reference, 0, sizeof(reference[0]));
4233 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4235 return (construct_type_t*)reference;
4238 static construct_type_t *parse_array_declarator(void)
4241 add_anchor_token(']');
4243 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4244 memset(array, 0, sizeof(array[0]));
4245 array->construct_type.kind = CONSTRUCT_ARRAY;
4247 if (token.type == T_static) {
4248 array->is_static = true;
4252 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4253 if (type_qualifiers != 0) {
4254 if (token.type == T_static) {
4255 array->is_static = true;
4259 array->type_qualifiers = type_qualifiers;
4261 if (token.type == '*' && look_ahead(1)->type == ']') {
4262 array->is_variable = true;
4264 } else if (token.type != ']') {
4265 array->size = parse_assignment_expression();
4268 rem_anchor_token(']');
4272 return &array->construct_type;
4275 static construct_type_t *parse_function_declarator(scope_t *scope,
4276 decl_modifiers_t modifiers)
4278 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4279 function_type_t *ftype = &type->function;
4281 ftype->linkage = current_linkage;
4283 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4284 case DM_NONE: break;
4285 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4286 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4287 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4288 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4291 errorf(HERE, "multiple calling conventions in declaration");
4295 parse_parameters(ftype, scope);
4297 construct_function_type_t *construct_function_type =
4298 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4299 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4300 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4301 construct_function_type->function_type = type;
4303 return &construct_function_type->construct_type;
4306 typedef struct parse_declarator_env_t {
4307 decl_modifiers_t modifiers;
4309 source_position_t source_position;
4311 } parse_declarator_env_t;
4313 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4314 bool may_be_abstract)
4316 /* construct a single linked list of construct_type_t's which describe
4317 * how to construct the final declarator type */
4318 construct_type_t *first = NULL;
4319 construct_type_t *last = NULL;
4320 gnu_attribute_t *attributes = NULL;
4322 decl_modifiers_t modifiers = parse_attributes(&attributes);
4324 /* MS __based extension */
4325 based_spec_t base_spec;
4326 base_spec.base_variable = NULL;
4329 construct_type_t *type;
4330 switch (token.type) {
4332 if (!(c_mode & _CXX))
4333 errorf(HERE, "references are only available for C++");
4334 if (base_spec.base_variable != NULL)
4335 warningf(&base_spec.source_position,
4336 "__based does not precede a pointer operator, ignored");
4337 type = parse_reference_declarator();
4339 base_spec.base_variable = NULL;
4343 type = parse_pointer_declarator(base_spec.base_variable);
4345 base_spec.base_variable = NULL;
4351 add_anchor_token(')');
4352 parse_microsoft_based(&base_spec);
4353 rem_anchor_token(')');
4358 goto ptr_operator_end;
4369 /* TODO: find out if this is correct */
4370 modifiers |= parse_attributes(&attributes);
4373 if (base_spec.base_variable != NULL)
4374 warningf(&base_spec.source_position,
4375 "__based does not precede a pointer operator, ignored");
4378 modifiers |= env->modifiers;
4379 env->modifiers = modifiers;
4382 construct_type_t *inner_types = NULL;
4384 switch (token.type) {
4387 errorf(HERE, "no identifier expected in typename");
4389 env->symbol = token.v.symbol;
4390 env->source_position = token.source_position;
4396 add_anchor_token(')');
4397 inner_types = parse_inner_declarator(env, may_be_abstract);
4398 if (inner_types != NULL) {
4399 /* All later declarators only modify the return type */
4402 rem_anchor_token(')');
4406 if (may_be_abstract)
4408 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4413 construct_type_t *p = last;
4416 construct_type_t *type;
4417 switch (token.type) {
4419 scope_t *scope = NULL;
4421 scope = &env->parameters;
4423 type = parse_function_declarator(scope, modifiers);
4427 type = parse_array_declarator();
4430 goto declarator_finished;
4433 /* insert in the middle of the list (behind p) */
4435 type->next = p->next;
4446 declarator_finished:
4447 /* append inner_types at the end of the list, we don't to set last anymore
4448 * as it's not needed anymore */
4450 assert(first == NULL);
4451 first = inner_types;
4453 last->next = inner_types;
4461 static void parse_declaration_attributes(entity_t *entity)
4463 gnu_attribute_t *attributes = NULL;
4464 decl_modifiers_t modifiers = parse_attributes(&attributes);
4470 if (entity->kind == ENTITY_TYPEDEF) {
4471 modifiers |= entity->typedefe.modifiers;
4472 type = entity->typedefe.type;
4474 assert(is_declaration(entity));
4475 modifiers |= entity->declaration.modifiers;
4476 type = entity->declaration.type;
4481 /* handle these strange/stupid mode attributes */
4482 gnu_attribute_t *attribute = attributes;
4483 for ( ; attribute != NULL; attribute = attribute->next) {
4484 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4487 atomic_type_kind_t akind = attribute->u.akind;
4488 if (!is_type_signed(type)) {
4490 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4491 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4492 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4493 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4495 panic("invalid akind in mode attribute");
4499 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4500 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4501 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4502 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4504 panic("invalid akind in mode attribute");
4508 type = make_atomic_type(akind, type->base.qualifiers);
4511 type_modifiers_t type_modifiers = type->base.modifiers;
4512 if (modifiers & DM_TRANSPARENT_UNION)
4513 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4515 if (type->base.modifiers != type_modifiers) {
4516 type_t *copy = duplicate_type(type);
4517 copy->base.modifiers = type_modifiers;
4519 type = typehash_insert(copy);
4521 obstack_free(type_obst, copy);
4525 if (entity->kind == ENTITY_TYPEDEF) {
4526 entity->typedefe.type = type;
4527 entity->typedefe.modifiers = modifiers;
4529 entity->declaration.type = type;
4530 entity->declaration.modifiers = modifiers;
4534 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4536 construct_type_t *iter = construct_list;
4537 for (; iter != NULL; iter = iter->next) {
4538 switch (iter->kind) {
4539 case CONSTRUCT_INVALID:
4540 internal_errorf(HERE, "invalid type construction found");
4541 case CONSTRUCT_FUNCTION: {
4542 construct_function_type_t *construct_function_type
4543 = (construct_function_type_t*) iter;
4545 type_t *function_type = construct_function_type->function_type;
4547 function_type->function.return_type = type;
4549 type_t *skipped_return_type = skip_typeref(type);
4551 if (is_type_function(skipped_return_type)) {
4552 errorf(HERE, "function returning function is not allowed");
4553 } else if (is_type_array(skipped_return_type)) {
4554 errorf(HERE, "function returning array is not allowed");
4556 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4558 "type qualifiers in return type of function type are meaningless");
4562 type = function_type;
4566 case CONSTRUCT_POINTER: {
4567 if (is_type_reference(skip_typeref(type)))
4568 errorf(HERE, "cannot declare a pointer to reference");
4570 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4571 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4575 case CONSTRUCT_REFERENCE:
4576 if (is_type_reference(skip_typeref(type)))
4577 errorf(HERE, "cannot declare a reference to reference");
4579 type = make_reference_type(type);
4582 case CONSTRUCT_ARRAY: {
4583 if (is_type_reference(skip_typeref(type)))
4584 errorf(HERE, "cannot declare an array of references");
4586 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4587 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4589 expression_t *size_expression = parsed_array->size;
4590 if (size_expression != NULL) {
4592 = create_implicit_cast(size_expression, type_size_t);
4595 array_type->base.qualifiers = parsed_array->type_qualifiers;
4596 array_type->array.element_type = type;
4597 array_type->array.is_static = parsed_array->is_static;
4598 array_type->array.is_variable = parsed_array->is_variable;
4599 array_type->array.size_expression = size_expression;
4601 if (size_expression != NULL) {
4602 if (is_constant_expression(size_expression)) {
4603 array_type->array.size_constant = true;
4604 array_type->array.size
4605 = fold_constant(size_expression);
4607 array_type->array.is_vla = true;
4611 type_t *skipped_type = skip_typeref(type);
4613 if (is_type_incomplete(skipped_type)) {
4614 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4615 } else if (is_type_function(skipped_type)) {
4616 errorf(HERE, "array of functions is not allowed");
4623 type_t *hashed_type = typehash_insert(type);
4624 if (hashed_type != type) {
4625 /* the function type was constructed earlier freeing it here will
4626 * destroy other types... */
4627 if (iter->kind != CONSTRUCT_FUNCTION) {
4637 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4638 bool may_be_abstract,
4639 bool create_compound_member)
4641 parse_declarator_env_t env;
4642 memset(&env, 0, sizeof(env));
4643 env.modifiers = specifiers->modifiers;
4645 construct_type_t *construct_type
4646 = parse_inner_declarator(&env, may_be_abstract);
4647 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4649 if (construct_type != NULL) {
4650 obstack_free(&temp_obst, construct_type);
4654 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4655 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4656 entity->base.symbol = env.symbol;
4657 entity->base.source_position = env.source_position;
4658 entity->typedefe.type = type;
4660 if (anonymous_entity != NULL) {
4661 if (is_type_compound(type)) {
4662 assert(anonymous_entity->compound.alias == NULL);
4663 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4664 anonymous_entity->kind == ENTITY_UNION);
4665 anonymous_entity->compound.alias = entity;
4666 anonymous_entity = NULL;
4667 } else if (is_type_enum(type)) {
4668 assert(anonymous_entity->enume.alias == NULL);
4669 assert(anonymous_entity->kind == ENTITY_ENUM);
4670 anonymous_entity->enume.alias = entity;
4671 anonymous_entity = NULL;
4675 if (create_compound_member) {
4676 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4677 } else if (is_type_function(skip_typeref(type))) {
4678 entity = allocate_entity_zero(ENTITY_FUNCTION);
4680 entity->function.is_inline = specifiers->is_inline;
4681 entity->function.parameters = env.parameters;
4683 entity = allocate_entity_zero(ENTITY_VARIABLE);
4685 entity->variable.get_property_sym = specifiers->get_property_sym;
4686 entity->variable.put_property_sym = specifiers->put_property_sym;
4687 if (specifiers->alignment != 0) {
4688 /* TODO: add checks here */
4689 entity->variable.alignment = specifiers->alignment;
4692 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4693 warningf(&env.source_position,
4694 "variable '%Y' declared 'inline'\n", env.symbol);
4698 entity->base.source_position = env.source_position;
4699 entity->base.symbol = env.symbol;
4700 entity->base.namespc = NAMESPACE_NORMAL;
4701 entity->declaration.type = type;
4702 entity->declaration.modifiers = env.modifiers;
4703 entity->declaration.deprecated_string = specifiers->deprecated_string;
4705 storage_class_t storage_class = specifiers->storage_class;
4706 entity->declaration.declared_storage_class = storage_class;
4708 if (storage_class == STORAGE_CLASS_NONE
4709 && current_scope != file_scope) {
4710 storage_class = STORAGE_CLASS_AUTO;
4712 entity->declaration.storage_class = storage_class;
4715 parse_declaration_attributes(entity);
4720 static type_t *parse_abstract_declarator(type_t *base_type)
4722 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4724 type_t *result = construct_declarator_type(construct_type, base_type);
4725 if (construct_type != NULL) {
4726 obstack_free(&temp_obst, construct_type);
4733 * Check if the declaration of main is suspicious. main should be a
4734 * function with external linkage, returning int, taking either zero
4735 * arguments, two, or three arguments of appropriate types, ie.
4737 * int main([ int argc, char **argv [, char **env ] ]).
4739 * @param decl the declaration to check
4740 * @param type the function type of the declaration
4742 static void check_type_of_main(const entity_t *entity)
4744 const source_position_t *pos = &entity->base.source_position;
4745 if (entity->kind != ENTITY_FUNCTION) {
4746 warningf(pos, "'main' is not a function");
4750 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4751 warningf(pos, "'main' is normally a non-static function");
4754 type_t *type = skip_typeref(entity->declaration.type);
4755 assert(is_type_function(type));
4757 function_type_t *func_type = &type->function;
4758 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4759 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4760 func_type->return_type);
4762 const function_parameter_t *parm = func_type->parameters;
4764 type_t *const first_type = parm->type;
4765 if (!types_compatible(skip_typeref(first_type), type_int)) {
4767 "first argument of 'main' should be 'int', but is '%T'",
4772 type_t *const second_type = parm->type;
4773 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4774 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4778 type_t *const third_type = parm->type;
4779 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4780 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4784 goto warn_arg_count;
4788 warningf(pos, "'main' takes only zero, two or three arguments");
4794 * Check if a symbol is the equal to "main".
4796 static bool is_sym_main(const symbol_t *const sym)
4798 return strcmp(sym->string, "main") == 0;
4801 static const char *get_entity_kind_name(entity_kind_t kind)
4803 switch ((entity_kind_tag_t) kind) {
4804 case ENTITY_FUNCTION: return "function";
4805 case ENTITY_VARIABLE: return "variable";
4806 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4807 case ENTITY_STRUCT: return "struct";
4808 case ENTITY_UNION: return "union";
4809 case ENTITY_ENUM: return "enum";
4810 case ENTITY_ENUM_VALUE: return "enum value";
4811 case ENTITY_LABEL: return "label";
4812 case ENTITY_LOCAL_LABEL: return "local label";
4813 case ENTITY_TYPEDEF: return "typedef";
4814 case ENTITY_NAMESPACE: return "namespace";
4815 case ENTITY_INVALID: break;
4818 panic("Invalid entity kind encountered in get_entity_kind_name");
4821 static void error_redefined_as_different_kind(const source_position_t *pos,
4822 const entity_t *old, entity_kind_t new_kind)
4824 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4825 get_entity_kind_name(old->kind), old->base.symbol,
4826 get_entity_kind_name(new_kind), &old->base.source_position);
4830 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4831 * for various problems that occur for multiple definitions
4833 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4835 const symbol_t *const symbol = entity->base.symbol;
4836 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4837 const source_position_t *pos = &entity->base.source_position;
4839 assert(symbol != NULL);
4840 entity_t *previous_entity = get_entity(symbol, namespc);
4841 /* pushing the same entity twice will break the stack structure */
4842 assert(previous_entity != entity);
4844 if (entity->kind == ENTITY_FUNCTION) {
4845 type_t *const orig_type = entity->declaration.type;
4846 type_t *const type = skip_typeref(orig_type);
4848 assert(is_type_function(type));
4849 if (type->function.unspecified_parameters &&
4850 warning.strict_prototypes &&
4851 previous_entity == NULL) {
4852 warningf(pos, "function declaration '%#T' is not a prototype",
4856 if (warning.main && current_scope == file_scope
4857 && is_sym_main(symbol)) {
4858 check_type_of_main(entity);
4862 if (is_declaration(entity)) {
4863 if (warning.nested_externs
4864 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4865 && current_scope != file_scope) {
4866 warningf(pos, "nested extern declaration of '%#T'",
4867 entity->declaration.type, symbol);
4871 if (previous_entity != NULL
4872 && previous_entity->base.parent_scope == ¤t_function->parameters
4873 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4875 assert(previous_entity->kind == ENTITY_VARIABLE);
4877 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4878 entity->declaration.type, symbol,
4879 previous_entity->declaration.type, symbol,
4880 &previous_entity->base.source_position);
4884 if (previous_entity != NULL
4885 && previous_entity->base.parent_scope == current_scope) {
4887 if (previous_entity->kind != entity->kind) {
4888 error_redefined_as_different_kind(pos, previous_entity,
4892 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4894 "redeclaration of enum entry '%Y' (declared %P)",
4895 symbol, &previous_entity->base.source_position);
4898 if (previous_entity->kind == ENTITY_TYPEDEF) {
4899 /* TODO: C++ allows this for exactly the same type */
4901 "redefinition of typedef '%Y' (declared %P)",
4902 symbol, &previous_entity->base.source_position);
4906 /* at this point we should have only VARIABLES or FUNCTIONS */
4907 assert(is_declaration(previous_entity) && is_declaration(entity));
4909 /* can happen for K&R style declarations */
4910 if (previous_entity->kind == ENTITY_VARIABLE
4911 && previous_entity->declaration.type == NULL
4912 && entity->kind == ENTITY_VARIABLE) {
4913 previous_entity->declaration.type = entity->declaration.type;
4914 previous_entity->declaration.storage_class
4915 = entity->declaration.storage_class;
4916 previous_entity->declaration.declared_storage_class
4917 = entity->declaration.declared_storage_class;
4918 previous_entity->declaration.modifiers
4919 = entity->declaration.modifiers;
4920 previous_entity->declaration.deprecated_string
4921 = entity->declaration.deprecated_string;
4923 assert(entity->declaration.type != NULL);
4925 declaration_t *const previous_declaration
4926 = &previous_entity->declaration;
4927 declaration_t *const declaration = &entity->declaration;
4928 type_t *const orig_type = entity->declaration.type;
4929 type_t *const type = skip_typeref(orig_type);
4931 type_t *prev_type = skip_typeref(previous_declaration->type);
4933 if (!types_compatible(type, prev_type)) {
4935 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4936 orig_type, symbol, previous_declaration->type, symbol,
4937 &previous_entity->base.source_position);
4939 unsigned old_storage_class = previous_declaration->storage_class;
4940 if (warning.redundant_decls && is_definition
4941 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4942 && !(previous_declaration->modifiers & DM_USED)
4943 && !previous_declaration->used) {
4944 warningf(&previous_entity->base.source_position,
4945 "unnecessary static forward declaration for '%#T'",
4946 previous_declaration->type, symbol);
4949 unsigned new_storage_class = declaration->storage_class;
4950 if (is_type_incomplete(prev_type)) {
4951 previous_declaration->type = type;
4955 /* pretend no storage class means extern for function
4956 * declarations (except if the previous declaration is neither
4957 * none nor extern) */
4958 if (entity->kind == ENTITY_FUNCTION) {
4959 if (prev_type->function.unspecified_parameters) {
4960 previous_declaration->type = type;
4964 switch (old_storage_class) {
4965 case STORAGE_CLASS_NONE:
4966 old_storage_class = STORAGE_CLASS_EXTERN;
4969 case STORAGE_CLASS_EXTERN:
4970 if (is_definition) {
4971 if (warning.missing_prototypes &&
4972 prev_type->function.unspecified_parameters &&
4973 !is_sym_main(symbol)) {
4974 warningf(pos, "no previous prototype for '%#T'",
4977 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4978 new_storage_class = STORAGE_CLASS_EXTERN;
4987 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4988 new_storage_class == STORAGE_CLASS_EXTERN) {
4989 warn_redundant_declaration:
4990 if (!is_definition &&
4991 warning.redundant_decls &&
4992 is_type_valid(prev_type) &&
4993 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4995 "redundant declaration for '%Y' (declared %P)",
4996 symbol, &previous_entity->base.source_position);
4998 } else if (current_function == NULL) {
4999 if (old_storage_class != STORAGE_CLASS_STATIC &&
5000 new_storage_class == STORAGE_CLASS_STATIC) {
5002 "static declaration of '%Y' follows non-static declaration (declared %P)",
5003 symbol, &previous_entity->base.source_position);
5004 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5005 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5006 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5008 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5010 goto error_redeclaration;
5011 goto warn_redundant_declaration;
5013 } else if (is_type_valid(prev_type)) {
5014 if (old_storage_class == new_storage_class) {
5015 error_redeclaration:
5016 errorf(pos, "redeclaration of '%Y' (declared %P)",
5017 symbol, &previous_entity->base.source_position);
5020 "redeclaration of '%Y' with different linkage (declared %P)",
5021 symbol, &previous_entity->base.source_position);
5026 previous_declaration->modifiers |= declaration->modifiers;
5027 if (entity->kind == ENTITY_FUNCTION) {
5028 previous_entity->function.is_inline |= entity->function.is_inline;
5030 return previous_entity;
5033 if (entity->kind == ENTITY_FUNCTION) {
5034 if (is_definition &&
5035 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5036 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5037 warningf(pos, "no previous prototype for '%#T'",
5038 entity->declaration.type, symbol);
5039 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5040 warningf(pos, "no previous declaration for '%#T'",
5041 entity->declaration.type, symbol);
5044 } else if (warning.missing_declarations
5045 && entity->kind == ENTITY_VARIABLE
5046 && current_scope == file_scope) {
5047 declaration_t *declaration = &entity->declaration;
5048 if (declaration->storage_class == STORAGE_CLASS_NONE ||
5049 declaration->storage_class == STORAGE_CLASS_THREAD) {
5050 warningf(pos, "no previous declaration for '%#T'",
5051 declaration->type, symbol);
5056 assert(entity->base.parent_scope == NULL);
5057 assert(current_scope != NULL);
5059 entity->base.parent_scope = current_scope;
5060 entity->base.namespc = NAMESPACE_NORMAL;
5061 environment_push(entity);
5062 append_entity(current_scope, entity);
5067 static void parser_error_multiple_definition(entity_t *entity,
5068 const source_position_t *source_position)
5070 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5071 entity->base.symbol, &entity->base.source_position);
5074 static bool is_declaration_specifier(const token_t *token,
5075 bool only_specifiers_qualifiers)
5077 switch (token->type) {
5082 return is_typedef_symbol(token->v.symbol);
5084 case T___extension__:
5086 return !only_specifiers_qualifiers;
5093 static void parse_init_declarator_rest(entity_t *entity)
5095 assert(is_declaration(entity));
5096 declaration_t *const declaration = &entity->declaration;
5100 type_t *orig_type = declaration->type;
5101 type_t *type = skip_typeref(orig_type);
5103 if (entity->kind == ENTITY_VARIABLE
5104 && entity->variable.initializer != NULL) {
5105 parser_error_multiple_definition(entity, HERE);
5108 bool must_be_constant = false;
5109 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5110 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5111 entity->base.parent_scope == file_scope) {
5112 must_be_constant = true;
5115 if (is_type_function(type)) {
5116 errorf(&entity->base.source_position,
5117 "function '%#T' is initialized like a variable",
5118 orig_type, entity->base.symbol);
5119 orig_type = type_error_type;
5122 parse_initializer_env_t env;
5123 env.type = orig_type;
5124 env.must_be_constant = must_be_constant;
5125 env.entity = entity;
5126 current_init_decl = entity;
5128 initializer_t *initializer = parse_initializer(&env);
5129 current_init_decl = NULL;
5131 if (entity->kind == ENTITY_VARIABLE) {
5132 /* § 6.7.5 (22) array initializers for arrays with unknown size
5133 * determine the array type size */
5134 declaration->type = env.type;
5135 entity->variable.initializer = initializer;
5139 /* parse rest of a declaration without any declarator */
5140 static void parse_anonymous_declaration_rest(
5141 const declaration_specifiers_t *specifiers)
5144 anonymous_entity = NULL;
5146 if (warning.other) {
5147 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5148 warningf(&specifiers->source_position,
5149 "useless storage class in empty declaration");
5152 type_t *type = specifiers->type;
5153 switch (type->kind) {
5154 case TYPE_COMPOUND_STRUCT:
5155 case TYPE_COMPOUND_UNION: {
5156 if (type->compound.compound->base.symbol == NULL) {
5157 warningf(&specifiers->source_position,
5158 "unnamed struct/union that defines no instances");
5167 warningf(&specifiers->source_position, "empty declaration");
5173 static void check_variable_type_complete(entity_t *ent)
5175 if (ent->kind != ENTITY_VARIABLE)
5178 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5179 * type for the object shall be complete [...] */
5180 declaration_t *decl = &ent->declaration;
5181 if (decl->storage_class != STORAGE_CLASS_NONE)
5184 type_t *type = decl->type;
5185 if (!is_type_incomplete(skip_typeref(type)))
5188 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5189 type, ent->base.symbol);
5193 static void parse_declaration_rest(entity_t *ndeclaration,
5194 const declaration_specifiers_t *specifiers,
5195 parsed_declaration_func finished_declaration)
5197 add_anchor_token(';');
5198 add_anchor_token(',');
5200 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5202 if (token.type == '=') {
5203 parse_init_declarator_rest(entity);
5206 check_variable_type_complete(entity);
5208 if (token.type != ',')
5212 add_anchor_token('=');
5213 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5214 rem_anchor_token('=');
5219 anonymous_entity = NULL;
5220 rem_anchor_token(';');
5221 rem_anchor_token(',');
5224 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5226 symbol_t *symbol = entity->base.symbol;
5227 if (symbol == NULL) {
5228 errorf(HERE, "anonymous declaration not valid as function parameter");
5232 assert(entity->base.namespc == NAMESPACE_NORMAL);
5233 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5234 if (previous_entity == NULL
5235 || previous_entity->base.parent_scope != current_scope) {
5236 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5241 if (is_definition) {
5242 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5245 return record_entity(entity, false);
5248 static void parse_declaration(parsed_declaration_func finished_declaration)
5250 declaration_specifiers_t specifiers;
5251 memset(&specifiers, 0, sizeof(specifiers));
5253 add_anchor_token(';');
5254 parse_declaration_specifiers(&specifiers);
5255 rem_anchor_token(';');
5257 if (token.type == ';') {
5258 parse_anonymous_declaration_rest(&specifiers);
5260 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5261 parse_declaration_rest(entity, &specifiers, finished_declaration);
5265 static type_t *get_default_promoted_type(type_t *orig_type)
5267 type_t *result = orig_type;
5269 type_t *type = skip_typeref(orig_type);
5270 if (is_type_integer(type)) {
5271 result = promote_integer(type);
5272 } else if (type == type_float) {
5273 result = type_double;
5279 static void parse_kr_declaration_list(entity_t *entity)
5281 if (entity->kind != ENTITY_FUNCTION)
5284 type_t *type = skip_typeref(entity->declaration.type);
5285 assert(is_type_function(type));
5286 if (!type->function.kr_style_parameters)
5290 add_anchor_token('{');
5292 /* push function parameters */
5293 size_t const top = environment_top();
5294 scope_push(&entity->function.parameters);
5296 entity_t *parameter = entity->function.parameters.entities;
5297 for ( ; parameter != NULL; parameter = parameter->base.next) {
5298 assert(parameter->base.parent_scope == NULL);
5299 parameter->base.parent_scope = current_scope;
5300 environment_push(parameter);
5303 /* parse declaration list */
5304 while (is_declaration_specifier(&token, false)) {
5305 parse_declaration(finished_kr_declaration);
5308 /* pop function parameters */
5309 assert(current_scope == &entity->function.parameters);
5311 environment_pop_to(top);
5313 /* update function type */
5314 type_t *new_type = duplicate_type(type);
5316 function_parameter_t *parameters = NULL;
5317 function_parameter_t *last_parameter = NULL;
5319 entity_t *parameter_declaration = entity->function.parameters.entities;
5320 for (; parameter_declaration != NULL;
5321 parameter_declaration = parameter_declaration->base.next) {
5322 type_t *parameter_type = parameter_declaration->declaration.type;
5323 if (parameter_type == NULL) {
5325 errorf(HERE, "no type specified for function parameter '%Y'",
5326 parameter_declaration->base.symbol);
5328 if (warning.implicit_int) {
5329 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5330 parameter_declaration->base.symbol);
5332 parameter_type = type_int;
5333 parameter_declaration->declaration.type = parameter_type;
5337 semantic_parameter(¶meter_declaration->declaration);
5338 parameter_type = parameter_declaration->declaration.type;
5341 * we need the default promoted types for the function type
5343 parameter_type = get_default_promoted_type(parameter_type);
5345 function_parameter_t *function_parameter
5346 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5347 memset(function_parameter, 0, sizeof(function_parameter[0]));
5349 function_parameter->type = parameter_type;
5350 if (last_parameter != NULL) {
5351 last_parameter->next = function_parameter;
5353 parameters = function_parameter;
5355 last_parameter = function_parameter;
5358 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5360 new_type->function.parameters = parameters;
5361 new_type->function.unspecified_parameters = true;
5363 type = typehash_insert(new_type);
5364 if (type != new_type) {
5365 obstack_free(type_obst, new_type);
5368 entity->declaration.type = type;
5370 rem_anchor_token('{');
5373 static bool first_err = true;
5376 * When called with first_err set, prints the name of the current function,
5379 static void print_in_function(void)
5383 diagnosticf("%s: In function '%Y':\n",
5384 current_function->base.base.source_position.input_name,
5385 current_function->base.base.symbol);
5390 * Check if all labels are defined in the current function.
5391 * Check if all labels are used in the current function.
5393 static void check_labels(void)
5395 for (const goto_statement_t *goto_statement = goto_first;
5396 goto_statement != NULL;
5397 goto_statement = goto_statement->next) {
5398 /* skip computed gotos */
5399 if (goto_statement->expression != NULL)
5402 label_t *label = goto_statement->label;
5405 if (label->base.source_position.input_name == NULL) {
5406 print_in_function();
5407 errorf(&goto_statement->base.source_position,
5408 "label '%Y' used but not defined", label->base.symbol);
5412 if (warning.unused_label) {
5413 for (const label_statement_t *label_statement = label_first;
5414 label_statement != NULL;
5415 label_statement = label_statement->next) {
5416 label_t *label = label_statement->label;
5418 if (! label->used) {
5419 print_in_function();
5420 warningf(&label_statement->base.source_position,
5421 "label '%Y' defined but not used", label->base.symbol);
5427 static void warn_unused_decl(entity_t *entity, entity_t *end,
5428 char const *const what)
5430 for (; entity != NULL; entity = entity->base.next) {
5431 if (!is_declaration(entity))
5434 declaration_t *declaration = &entity->declaration;
5435 if (declaration->implicit)
5438 if (!declaration->used) {
5439 print_in_function();
5440 warningf(&entity->base.source_position, "%s '%Y' is unused",
5441 what, entity->base.symbol);
5442 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5443 print_in_function();
5444 warningf(&entity->base.source_position, "%s '%Y' is never read",
5445 what, entity->base.symbol);
5453 static void check_unused_variables(statement_t *const stmt, void *const env)
5457 switch (stmt->kind) {
5458 case STATEMENT_DECLARATION: {
5459 declaration_statement_t const *const decls = &stmt->declaration;
5460 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5466 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5475 * Check declarations of current_function for unused entities.
5477 static void check_declarations(void)
5479 if (warning.unused_parameter) {
5480 const scope_t *scope = ¤t_function->parameters;
5482 /* do not issue unused warnings for main */
5483 if (!is_sym_main(current_function->base.base.symbol)) {
5484 warn_unused_decl(scope->entities, NULL, "parameter");
5487 if (warning.unused_variable) {
5488 walk_statements(current_function->statement, check_unused_variables,
5493 static int determine_truth(expression_t const* const cond)
5496 !is_constant_expression(cond) ? 0 :
5497 fold_constant(cond) != 0 ? 1 :
5501 static bool expression_returns(expression_t const *const expr)
5503 switch (expr->kind) {
5505 expression_t const *const func = expr->call.function;
5506 if (func->kind == EXPR_REFERENCE) {
5507 entity_t *entity = func->reference.entity;
5508 if (entity->kind == ENTITY_FUNCTION
5509 && entity->declaration.modifiers & DM_NORETURN)
5513 if (!expression_returns(func))
5516 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5517 if (!expression_returns(arg->expression))
5524 case EXPR_REFERENCE:
5525 case EXPR_REFERENCE_ENUM_VALUE:
5527 case EXPR_CHARACTER_CONSTANT:
5528 case EXPR_WIDE_CHARACTER_CONSTANT:
5529 case EXPR_STRING_LITERAL:
5530 case EXPR_WIDE_STRING_LITERAL:
5531 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5532 case EXPR_LABEL_ADDRESS:
5533 case EXPR_CLASSIFY_TYPE:
5534 case EXPR_SIZEOF: // TODO handle obscure VLA case
5537 case EXPR_BUILTIN_SYMBOL:
5538 case EXPR_BUILTIN_CONSTANT_P:
5539 case EXPR_BUILTIN_PREFETCH:
5542 case EXPR_STATEMENT: // TODO implement
5545 case EXPR_CONDITIONAL:
5546 // TODO handle constant expression
5548 expression_returns(expr->conditional.condition) && (
5549 expression_returns(expr->conditional.true_expression) ||
5550 expression_returns(expr->conditional.false_expression)
5554 return expression_returns(expr->select.compound);
5556 case EXPR_ARRAY_ACCESS:
5558 expression_returns(expr->array_access.array_ref) &&
5559 expression_returns(expr->array_access.index);
5562 return expression_returns(expr->va_starte.ap);
5565 return expression_returns(expr->va_arge.ap);
5567 EXPR_UNARY_CASES_MANDATORY
5568 return expression_returns(expr->unary.value);
5570 case EXPR_UNARY_THROW:
5574 // TODO handle constant lhs of && and ||
5576 expression_returns(expr->binary.left) &&
5577 expression_returns(expr->binary.right);
5583 panic("unhandled expression");
5586 static bool noreturn_candidate;
5588 static void check_reachable(statement_t *const stmt)
5590 if (stmt->base.reachable)
5592 if (stmt->kind != STATEMENT_DO_WHILE)
5593 stmt->base.reachable = true;
5595 statement_t *last = stmt;
5597 switch (stmt->kind) {
5598 case STATEMENT_INVALID:
5599 case STATEMENT_EMPTY:
5600 case STATEMENT_DECLARATION:
5601 case STATEMENT_LOCAL_LABEL:
5603 next = stmt->base.next;
5606 case STATEMENT_COMPOUND:
5607 next = stmt->compound.statements;
5610 case STATEMENT_RETURN:
5611 noreturn_candidate = false;
5614 case STATEMENT_IF: {
5615 if_statement_t const* const ifs = &stmt->ifs;
5616 int const val = determine_truth(ifs->condition);
5619 check_reachable(ifs->true_statement);
5624 if (ifs->false_statement != NULL) {
5625 check_reachable(ifs->false_statement);
5629 next = stmt->base.next;
5633 case STATEMENT_SWITCH: {
5634 switch_statement_t const *const switchs = &stmt->switchs;
5635 expression_t const *const expr = switchs->expression;
5637 if (is_constant_expression(expr)) {
5638 long const val = fold_constant(expr);
5639 case_label_statement_t * defaults = NULL;
5640 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5641 if (i->expression == NULL) {
5646 if (i->first_case <= val && val <= i->last_case) {
5647 check_reachable((statement_t*)i);
5652 if (defaults != NULL) {
5653 check_reachable((statement_t*)defaults);
5657 bool has_default = false;
5658 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5659 if (i->expression == NULL)
5662 check_reachable((statement_t*)i);
5669 next = stmt->base.next;
5673 case STATEMENT_EXPRESSION: {
5674 /* Check for noreturn function call */
5675 expression_t const *const expr = stmt->expression.expression;
5676 if (!expression_returns(expr))
5679 next = stmt->base.next;
5683 case STATEMENT_CONTINUE: {
5684 statement_t *parent = stmt;
5686 parent = parent->base.parent;
5687 if (parent == NULL) /* continue not within loop */
5691 switch (parent->kind) {
5692 case STATEMENT_WHILE: goto continue_while;
5693 case STATEMENT_DO_WHILE: goto continue_do_while;
5694 case STATEMENT_FOR: goto continue_for;
5701 case STATEMENT_BREAK: {
5702 statement_t *parent = stmt;
5704 parent = parent->base.parent;
5705 if (parent == NULL) /* break not within loop/switch */
5708 switch (parent->kind) {
5709 case STATEMENT_SWITCH:
5710 case STATEMENT_WHILE:
5711 case STATEMENT_DO_WHILE:
5714 next = parent->base.next;
5715 goto found_break_parent;
5724 case STATEMENT_GOTO:
5725 if (stmt->gotos.expression) {
5726 statement_t *parent = stmt->base.parent;
5727 if (parent == NULL) /* top level goto */
5731 next = stmt->gotos.label->statement;
5732 if (next == NULL) /* missing label */
5737 case STATEMENT_LABEL:
5738 next = stmt->label.statement;
5741 case STATEMENT_CASE_LABEL:
5742 next = stmt->case_label.statement;
5745 case STATEMENT_WHILE: {
5746 while_statement_t const *const whiles = &stmt->whiles;
5747 int const val = determine_truth(whiles->condition);
5750 check_reachable(whiles->body);
5755 next = stmt->base.next;
5759 case STATEMENT_DO_WHILE:
5760 next = stmt->do_while.body;
5763 case STATEMENT_FOR: {
5764 for_statement_t *const fors = &stmt->fors;
5766 if (fors->condition_reachable)
5768 fors->condition_reachable = true;
5770 expression_t const *const cond = fors->condition;
5772 cond == NULL ? 1 : determine_truth(cond);
5775 check_reachable(fors->body);
5780 next = stmt->base.next;
5784 case STATEMENT_MS_TRY: {
5785 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5786 check_reachable(ms_try->try_statement);
5787 next = ms_try->final_statement;
5791 case STATEMENT_LEAVE: {
5792 statement_t *parent = stmt;
5794 parent = parent->base.parent;
5795 if (parent == NULL) /* __leave not within __try */
5798 if (parent->kind == STATEMENT_MS_TRY) {
5800 next = parent->ms_try.final_statement;
5808 while (next == NULL) {
5809 next = last->base.parent;
5811 noreturn_candidate = false;
5813 type_t *const type = current_function->base.type;
5814 assert(is_type_function(type));
5815 type_t *const ret = skip_typeref(type->function.return_type);
5816 if (warning.return_type &&
5817 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5818 is_type_valid(ret) &&
5819 !is_sym_main(current_function->base.base.symbol)) {
5820 warningf(&stmt->base.source_position,
5821 "control reaches end of non-void function");
5826 switch (next->kind) {
5827 case STATEMENT_INVALID:
5828 case STATEMENT_EMPTY:
5829 case STATEMENT_DECLARATION:
5830 case STATEMENT_LOCAL_LABEL:
5831 case STATEMENT_EXPRESSION:
5833 case STATEMENT_RETURN:
5834 case STATEMENT_CONTINUE:
5835 case STATEMENT_BREAK:
5836 case STATEMENT_GOTO:
5837 case STATEMENT_LEAVE:
5838 panic("invalid control flow in function");
5840 case STATEMENT_COMPOUND:
5842 case STATEMENT_SWITCH:
5843 case STATEMENT_LABEL:
5844 case STATEMENT_CASE_LABEL:
5846 next = next->base.next;
5849 case STATEMENT_WHILE: {
5851 if (next->base.reachable)
5853 next->base.reachable = true;
5855 while_statement_t const *const whiles = &next->whiles;
5856 int const val = determine_truth(whiles->condition);
5859 check_reachable(whiles->body);
5865 next = next->base.next;
5869 case STATEMENT_DO_WHILE: {
5871 if (next->base.reachable)
5873 next->base.reachable = true;
5875 do_while_statement_t const *const dw = &next->do_while;
5876 int const val = determine_truth(dw->condition);
5879 check_reachable(dw->body);
5885 next = next->base.next;
5889 case STATEMENT_FOR: {
5891 for_statement_t *const fors = &next->fors;
5893 fors->step_reachable = true;
5895 if (fors->condition_reachable)
5897 fors->condition_reachable = true;
5899 expression_t const *const cond = fors->condition;
5901 cond == NULL ? 1 : determine_truth(cond);
5904 check_reachable(fors->body);
5910 next = next->base.next;
5914 case STATEMENT_MS_TRY:
5916 next = next->ms_try.final_statement;
5921 check_reachable(next);
5924 static void check_unreachable(statement_t* const stmt, void *const env)
5928 switch (stmt->kind) {
5929 case STATEMENT_DO_WHILE:
5930 if (!stmt->base.reachable) {
5931 expression_t const *const cond = stmt->do_while.condition;
5932 if (determine_truth(cond) >= 0) {
5933 warningf(&cond->base.source_position,
5934 "condition of do-while-loop is unreachable");
5939 case STATEMENT_FOR: {
5940 for_statement_t const* const fors = &stmt->fors;
5942 // if init and step are unreachable, cond is unreachable, too
5943 if (!stmt->base.reachable && !fors->step_reachable) {
5944 warningf(&stmt->base.source_position, "statement is unreachable");
5946 if (!stmt->base.reachable && fors->initialisation != NULL) {
5947 warningf(&fors->initialisation->base.source_position,
5948 "initialisation of for-statement is unreachable");
5951 if (!fors->condition_reachable && fors->condition != NULL) {
5952 warningf(&fors->condition->base.source_position,
5953 "condition of for-statement is unreachable");
5956 if (!fors->step_reachable && fors->step != NULL) {
5957 warningf(&fors->step->base.source_position,
5958 "step of for-statement is unreachable");
5964 case STATEMENT_COMPOUND:
5965 if (stmt->compound.statements != NULL)
5970 if (!stmt->base.reachable)
5971 warningf(&stmt->base.source_position, "statement is unreachable");
5976 static void parse_external_declaration(void)
5978 /* function-definitions and declarations both start with declaration
5980 declaration_specifiers_t specifiers;
5981 memset(&specifiers, 0, sizeof(specifiers));
5983 add_anchor_token(';');
5984 parse_declaration_specifiers(&specifiers);
5985 rem_anchor_token(';');
5987 /* must be a declaration */
5988 if (token.type == ';') {
5989 parse_anonymous_declaration_rest(&specifiers);
5993 add_anchor_token(',');
5994 add_anchor_token('=');
5995 add_anchor_token(';');
5996 add_anchor_token('{');
5998 /* declarator is common to both function-definitions and declarations */
5999 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
6001 rem_anchor_token('{');
6002 rem_anchor_token(';');
6003 rem_anchor_token('=');
6004 rem_anchor_token(',');
6006 /* must be a declaration */
6007 switch (token.type) {
6011 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6015 /* must be a function definition */
6016 parse_kr_declaration_list(ndeclaration);
6018 if (token.type != '{') {
6019 parse_error_expected("while parsing function definition", '{', NULL);
6020 eat_until_matching_token(';');
6024 assert(is_declaration(ndeclaration));
6025 type_t *type = skip_typeref(ndeclaration->declaration.type);
6027 if (!is_type_function(type)) {
6028 if (is_type_valid(type)) {
6029 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6030 type, ndeclaration->base.symbol);
6036 if (warning.aggregate_return &&
6037 is_type_compound(skip_typeref(type->function.return_type))) {
6038 warningf(HERE, "function '%Y' returns an aggregate",
6039 ndeclaration->base.symbol);
6041 if (warning.traditional && !type->function.unspecified_parameters) {
6042 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6043 ndeclaration->base.symbol);
6045 if (warning.old_style_definition && type->function.unspecified_parameters) {
6046 warningf(HERE, "old-style function definition '%Y'",
6047 ndeclaration->base.symbol);
6050 /* § 6.7.5.3 (14) a function definition with () means no
6051 * parameters (and not unspecified parameters) */
6052 if (type->function.unspecified_parameters
6053 && type->function.parameters == NULL
6054 && !type->function.kr_style_parameters) {
6055 type_t *duplicate = duplicate_type(type);
6056 duplicate->function.unspecified_parameters = false;
6058 type = typehash_insert(duplicate);
6059 if (type != duplicate) {
6060 obstack_free(type_obst, duplicate);
6062 ndeclaration->declaration.type = type;
6065 entity_t *const entity = record_entity(ndeclaration, true);
6066 assert(entity->kind == ENTITY_FUNCTION);
6067 assert(ndeclaration->kind == ENTITY_FUNCTION);
6069 function_t *function = &entity->function;
6070 if (ndeclaration != entity) {
6071 function->parameters = ndeclaration->function.parameters;
6073 assert(is_declaration(entity));
6074 type = skip_typeref(entity->declaration.type);
6076 /* push function parameters and switch scope */
6077 size_t const top = environment_top();
6078 scope_push(&function->parameters);
6080 entity_t *parameter = function->parameters.entities;
6081 for (; parameter != NULL; parameter = parameter->base.next) {
6082 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6083 parameter->base.parent_scope = current_scope;
6085 assert(parameter->base.parent_scope == NULL
6086 || parameter->base.parent_scope == current_scope);
6087 parameter->base.parent_scope = current_scope;
6088 if (parameter->base.symbol == NULL) {
6089 errorf(¶meter->base.source_position, "parameter name omitted");
6092 environment_push(parameter);
6095 if (function->statement != NULL) {
6096 parser_error_multiple_definition(entity, HERE);
6099 /* parse function body */
6100 int label_stack_top = label_top();
6101 function_t *old_current_function = current_function;
6102 current_function = function;
6103 current_parent = NULL;
6106 goto_anchor = &goto_first;
6108 label_anchor = &label_first;
6110 statement_t *const body = parse_compound_statement(false);
6111 function->statement = body;
6114 check_declarations();
6115 if (warning.return_type ||
6116 warning.unreachable_code ||
6117 (warning.missing_noreturn
6118 && !(function->base.modifiers & DM_NORETURN))) {
6119 noreturn_candidate = true;
6120 check_reachable(body);
6121 if (warning.unreachable_code)
6122 walk_statements(body, check_unreachable, NULL);
6123 if (warning.missing_noreturn &&
6124 noreturn_candidate &&
6125 !(function->base.modifiers & DM_NORETURN)) {
6126 warningf(&body->base.source_position,
6127 "function '%#T' is candidate for attribute 'noreturn'",
6128 type, entity->base.symbol);
6132 assert(current_parent == NULL);
6133 assert(current_function == function);
6134 current_function = old_current_function;
6135 label_pop_to(label_stack_top);
6138 assert(current_scope == &function->parameters);
6140 environment_pop_to(top);
6143 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6144 source_position_t *source_position,
6145 const symbol_t *symbol)
6147 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6149 type->bitfield.base_type = base_type;
6150 type->bitfield.size_expression = size;
6153 type_t *skipped_type = skip_typeref(base_type);
6154 if (!is_type_integer(skipped_type)) {
6155 errorf(HERE, "bitfield base type '%T' is not an integer type",
6159 bit_size = skipped_type->base.size * 8;
6162 if (is_constant_expression(size)) {
6163 long v = fold_constant(size);
6166 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6167 } else if (v == 0) {
6168 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6169 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6170 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6172 type->bitfield.bit_size = v;
6179 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6181 entity_t *iter = compound->members.entities;
6182 for (; iter != NULL; iter = iter->base.next) {
6183 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6186 if (iter->base.symbol == symbol) {
6188 } else if (iter->base.symbol == NULL) {
6189 type_t *type = skip_typeref(iter->declaration.type);
6190 if (is_type_compound(type)) {
6192 = find_compound_entry(type->compound.compound, symbol);
6203 static void parse_compound_declarators(compound_t *compound,
6204 const declaration_specifiers_t *specifiers)
6209 if (token.type == ':') {
6210 source_position_t source_position = *HERE;
6213 type_t *base_type = specifiers->type;
6214 expression_t *size = parse_constant_expression();
6216 type_t *type = make_bitfield_type(base_type, size,
6217 &source_position, sym_anonymous);
6219 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6220 entity->base.namespc = NAMESPACE_NORMAL;
6221 entity->base.source_position = source_position;
6222 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6223 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6224 entity->declaration.modifiers = specifiers->modifiers;
6225 entity->declaration.type = type;
6227 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6228 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6230 if (token.type == ':') {
6231 source_position_t source_position = *HERE;
6233 expression_t *size = parse_constant_expression();
6235 type_t *type = entity->declaration.type;
6236 type_t *bitfield_type = make_bitfield_type(type, size,
6237 &source_position, entity->base.symbol);
6238 entity->declaration.type = bitfield_type;
6242 /* make sure we don't define a symbol multiple times */
6243 symbol_t *symbol = entity->base.symbol;
6244 if (symbol != NULL) {
6245 entity_t *prev = find_compound_entry(compound, symbol);
6248 errorf(&entity->base.source_position,
6249 "multiple declarations of symbol '%Y' (declared %P)",
6250 symbol, &prev->base.source_position);
6254 append_entity(&compound->members, entity);
6256 type_t *orig_type = entity->declaration.type;
6257 type_t *type = skip_typeref(orig_type);
6258 if (is_type_function(type)) {
6259 errorf(&entity->base.source_position,
6260 "compound member '%Y' must not have function type '%T'",
6261 entity->base.symbol, orig_type);
6262 } else if (is_type_incomplete(type)) {
6263 /* §6.7.2.1:16 flexible array member */
6264 if (is_type_array(type) &&
6265 token.type == ';' &&
6266 look_ahead(1)->type == '}') {
6267 compound->has_flexible_member = true;
6269 errorf(&entity->base.source_position,
6270 "compound member '%Y' has incomplete type '%T'",
6271 entity->base.symbol, orig_type);
6275 if (token.type != ',')
6282 anonymous_entity = NULL;
6285 static void parse_compound_type_entries(compound_t *compound)
6288 add_anchor_token('}');
6290 while (token.type != '}') {
6291 if (token.type == T_EOF) {
6292 errorf(HERE, "EOF while parsing struct");
6295 declaration_specifiers_t specifiers;
6296 memset(&specifiers, 0, sizeof(specifiers));
6297 parse_declaration_specifiers(&specifiers);
6299 parse_compound_declarators(compound, &specifiers);
6301 rem_anchor_token('}');
6305 compound->complete = true;
6308 static type_t *parse_typename(void)
6310 declaration_specifiers_t specifiers;
6311 memset(&specifiers, 0, sizeof(specifiers));
6312 parse_declaration_specifiers(&specifiers);
6313 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6314 /* TODO: improve error message, user does probably not know what a
6315 * storage class is...
6317 errorf(HERE, "typename may not have a storage class");
6320 type_t *result = parse_abstract_declarator(specifiers.type);
6328 typedef expression_t* (*parse_expression_function)(void);
6329 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6331 typedef struct expression_parser_function_t expression_parser_function_t;
6332 struct expression_parser_function_t {
6333 parse_expression_function parser;
6334 unsigned infix_precedence;
6335 parse_expression_infix_function infix_parser;
6338 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6341 * Prints an error message if an expression was expected but not read
6343 static expression_t *expected_expression_error(void)
6345 /* skip the error message if the error token was read */
6346 if (token.type != T_ERROR) {
6347 errorf(HERE, "expected expression, got token '%K'", &token);
6351 return create_invalid_expression();
6355 * Parse a string constant.
6357 static expression_t *parse_string_const(void)
6360 if (token.type == T_STRING_LITERAL) {
6361 string_t res = token.v.string;
6363 while (token.type == T_STRING_LITERAL) {
6364 res = concat_strings(&res, &token.v.string);
6367 if (token.type != T_WIDE_STRING_LITERAL) {
6368 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6369 /* note: that we use type_char_ptr here, which is already the
6370 * automatic converted type. revert_automatic_type_conversion
6371 * will construct the array type */
6372 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6373 cnst->string.value = res;
6377 wres = concat_string_wide_string(&res, &token.v.wide_string);
6379 wres = token.v.wide_string;
6384 switch (token.type) {
6385 case T_WIDE_STRING_LITERAL:
6386 wres = concat_wide_strings(&wres, &token.v.wide_string);
6389 case T_STRING_LITERAL:
6390 wres = concat_wide_string_string(&wres, &token.v.string);
6394 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6395 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6396 cnst->wide_string.value = wres;
6405 * Parse a boolean constant.
6407 static expression_t *parse_bool_const(bool value)
6409 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6410 cnst->base.type = type_bool;
6411 cnst->conste.v.int_value = value;
6419 * Parse an integer constant.
6421 static expression_t *parse_int_const(void)
6423 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6424 cnst->base.type = token.datatype;
6425 cnst->conste.v.int_value = token.v.intvalue;
6433 * Parse a character constant.
6435 static expression_t *parse_character_constant(void)
6437 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6438 cnst->base.type = token.datatype;
6439 cnst->conste.v.character = token.v.string;
6441 if (cnst->conste.v.character.size != 1) {
6443 errorf(HERE, "more than 1 character in character constant");
6444 } else if (warning.multichar) {
6445 warningf(HERE, "multi-character character constant");
6454 * Parse a wide character constant.
6456 static expression_t *parse_wide_character_constant(void)
6458 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6459 cnst->base.type = token.datatype;
6460 cnst->conste.v.wide_character = token.v.wide_string;
6462 if (cnst->conste.v.wide_character.size != 1) {
6464 errorf(HERE, "more than 1 character in character constant");
6465 } else if (warning.multichar) {
6466 warningf(HERE, "multi-character character constant");
6475 * Parse a float constant.
6477 static expression_t *parse_float_const(void)
6479 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6480 cnst->base.type = token.datatype;
6481 cnst->conste.v.float_value = token.v.floatvalue;
6488 static entity_t *create_implicit_function(symbol_t *symbol,
6489 const source_position_t *source_position)
6491 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6492 ntype->function.return_type = type_int;
6493 ntype->function.unspecified_parameters = true;
6495 type_t *type = typehash_insert(ntype);
6496 if (type != ntype) {
6500 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6501 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6502 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6503 entity->declaration.type = type;
6504 entity->declaration.implicit = true;
6505 entity->base.symbol = symbol;
6506 entity->base.source_position = *source_position;
6508 bool strict_prototypes_old = warning.strict_prototypes;
6509 warning.strict_prototypes = false;
6510 record_entity(entity, false);
6511 warning.strict_prototypes = strict_prototypes_old;
6517 * Creates a return_type (func)(argument_type) function type if not
6520 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6521 type_t *argument_type2)
6523 function_parameter_t *parameter2
6524 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6525 memset(parameter2, 0, sizeof(parameter2[0]));
6526 parameter2->type = argument_type2;
6528 function_parameter_t *parameter1
6529 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6530 memset(parameter1, 0, sizeof(parameter1[0]));
6531 parameter1->type = argument_type1;
6532 parameter1->next = parameter2;
6534 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6535 type->function.return_type = return_type;
6536 type->function.parameters = parameter1;
6538 type_t *result = typehash_insert(type);
6539 if (result != type) {
6547 * Creates a return_type (func)(argument_type) function type if not
6550 * @param return_type the return type
6551 * @param argument_type the argument type
6553 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6555 function_parameter_t *parameter
6556 = obstack_alloc(type_obst, sizeof(parameter[0]));
6557 memset(parameter, 0, sizeof(parameter[0]));
6558 parameter->type = argument_type;
6560 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6561 type->function.return_type = return_type;
6562 type->function.parameters = parameter;
6564 type_t *result = typehash_insert(type);
6565 if (result != type) {
6572 static type_t *make_function_0_type(type_t *return_type)
6574 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6575 type->function.return_type = return_type;
6576 type->function.parameters = NULL;
6578 type_t *result = typehash_insert(type);
6579 if (result != type) {
6587 * Creates a function type for some function like builtins.
6589 * @param symbol the symbol describing the builtin
6591 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6593 switch (symbol->ID) {
6594 case T___builtin_alloca:
6595 return make_function_1_type(type_void_ptr, type_size_t);
6596 case T___builtin_huge_val:
6597 return make_function_0_type(type_double);
6598 case T___builtin_inf:
6599 return make_function_0_type(type_double);
6600 case T___builtin_inff:
6601 return make_function_0_type(type_float);
6602 case T___builtin_infl:
6603 return make_function_0_type(type_long_double);
6604 case T___builtin_nan:
6605 return make_function_1_type(type_double, type_char_ptr);
6606 case T___builtin_nanf:
6607 return make_function_1_type(type_float, type_char_ptr);
6608 case T___builtin_nanl:
6609 return make_function_1_type(type_long_double, type_char_ptr);
6610 case T___builtin_va_end:
6611 return make_function_1_type(type_void, type_valist);
6612 case T___builtin_expect:
6613 return make_function_2_type(type_long, type_long, type_long);
6615 internal_errorf(HERE, "not implemented builtin symbol found");
6620 * Performs automatic type cast as described in § 6.3.2.1.
6622 * @param orig_type the original type
6624 static type_t *automatic_type_conversion(type_t *orig_type)
6626 type_t *type = skip_typeref(orig_type);
6627 if (is_type_array(type)) {
6628 array_type_t *array_type = &type->array;
6629 type_t *element_type = array_type->element_type;
6630 unsigned qualifiers = array_type->base.qualifiers;
6632 return make_pointer_type(element_type, qualifiers);
6635 if (is_type_function(type)) {
6636 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6643 * reverts the automatic casts of array to pointer types and function
6644 * to function-pointer types as defined § 6.3.2.1
6646 type_t *revert_automatic_type_conversion(const expression_t *expression)
6648 switch (expression->kind) {
6649 case EXPR_REFERENCE: {
6650 entity_t *entity = expression->reference.entity;
6651 if (is_declaration(entity)) {
6652 return entity->declaration.type;
6653 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6654 return entity->enum_value.enum_type;
6656 panic("no declaration or enum in reference");
6661 entity_t *entity = expression->select.compound_entry;
6662 assert(is_declaration(entity));
6663 type_t *type = entity->declaration.type;
6664 return get_qualified_type(type,
6665 expression->base.type->base.qualifiers);
6668 case EXPR_UNARY_DEREFERENCE: {
6669 const expression_t *const value = expression->unary.value;
6670 type_t *const type = skip_typeref(value->base.type);
6671 assert(is_type_pointer(type));
6672 return type->pointer.points_to;
6675 case EXPR_BUILTIN_SYMBOL:
6676 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6678 case EXPR_ARRAY_ACCESS: {
6679 const expression_t *array_ref = expression->array_access.array_ref;
6680 type_t *type_left = skip_typeref(array_ref->base.type);
6681 if (!is_type_valid(type_left))
6683 assert(is_type_pointer(type_left));
6684 return type_left->pointer.points_to;
6687 case EXPR_STRING_LITERAL: {
6688 size_t size = expression->string.value.size;
6689 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6692 case EXPR_WIDE_STRING_LITERAL: {
6693 size_t size = expression->wide_string.value.size;
6694 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6697 case EXPR_COMPOUND_LITERAL:
6698 return expression->compound_literal.type;
6703 return expression->base.type;
6706 static expression_t *parse_reference(void)
6708 symbol_t *const symbol = token.v.symbol;
6710 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6712 if (entity == NULL) {
6713 if (!strict_mode && look_ahead(1)->type == '(') {
6714 /* an implicitly declared function */
6715 if (warning.implicit_function_declaration) {
6716 warningf(HERE, "implicit declaration of function '%Y'",
6720 entity = create_implicit_function(symbol, HERE);
6722 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6723 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6729 if (is_declaration(entity)) {
6730 orig_type = entity->declaration.type;
6731 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6732 orig_type = entity->enum_value.enum_type;
6733 } else if (entity->kind == ENTITY_TYPEDEF) {
6734 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6737 return create_invalid_expression();
6739 panic("expected declaration or enum value in reference");
6742 /* we always do the auto-type conversions; the & and sizeof parser contains
6743 * code to revert this! */
6744 type_t *type = automatic_type_conversion(orig_type);
6746 expression_kind_t kind = EXPR_REFERENCE;
6747 if (entity->kind == ENTITY_ENUM_VALUE)
6748 kind = EXPR_REFERENCE_ENUM_VALUE;
6750 expression_t *expression = allocate_expression_zero(kind);
6751 expression->reference.entity = entity;
6752 expression->base.type = type;
6754 /* this declaration is used */
6755 if (is_declaration(entity)) {
6756 entity->declaration.used = true;
6759 if (entity->base.parent_scope != file_scope
6760 && entity->base.parent_scope->depth < current_function->parameters.depth
6761 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6762 if (entity->kind == ENTITY_VARIABLE) {
6763 /* access of a variable from an outer function */
6764 entity->variable.address_taken = true;
6766 current_function->need_closure = true;
6769 /* check for deprecated functions */
6770 if (warning.deprecated_declarations
6771 && is_declaration(entity)
6772 && entity->declaration.modifiers & DM_DEPRECATED) {
6773 declaration_t *declaration = &entity->declaration;
6775 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6776 "function" : "variable";
6778 if (declaration->deprecated_string != NULL) {
6779 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6780 prefix, entity->base.symbol, &entity->base.source_position,
6781 declaration->deprecated_string);
6783 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6784 entity->base.symbol, &entity->base.source_position);
6788 if (warning.init_self && entity == current_init_decl && !in_type_prop
6789 && entity->kind == ENTITY_VARIABLE) {
6790 current_init_decl = NULL;
6791 warningf(HERE, "variable '%#T' is initialized by itself",
6792 entity->declaration.type, entity->base.symbol);
6799 static bool semantic_cast(expression_t *cast)
6801 expression_t *expression = cast->unary.value;
6802 type_t *orig_dest_type = cast->base.type;
6803 type_t *orig_type_right = expression->base.type;
6804 type_t const *dst_type = skip_typeref(orig_dest_type);
6805 type_t const *src_type = skip_typeref(orig_type_right);
6806 source_position_t const *pos = &cast->base.source_position;
6808 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6809 if (dst_type == type_void)
6812 /* only integer and pointer can be casted to pointer */
6813 if (is_type_pointer(dst_type) &&
6814 !is_type_pointer(src_type) &&
6815 !is_type_integer(src_type) &&
6816 is_type_valid(src_type)) {
6817 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6821 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6822 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6826 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6827 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6831 if (warning.cast_qual &&
6832 is_type_pointer(src_type) &&
6833 is_type_pointer(dst_type)) {
6834 type_t *src = skip_typeref(src_type->pointer.points_to);
6835 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6836 unsigned missing_qualifiers =
6837 src->base.qualifiers & ~dst->base.qualifiers;
6838 if (missing_qualifiers != 0) {
6840 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6841 missing_qualifiers, orig_type_right);
6847 static expression_t *parse_compound_literal(type_t *type)
6849 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6851 parse_initializer_env_t env;
6854 env.must_be_constant = false;
6855 initializer_t *initializer = parse_initializer(&env);
6858 expression->compound_literal.initializer = initializer;
6859 expression->compound_literal.type = type;
6860 expression->base.type = automatic_type_conversion(type);
6866 * Parse a cast expression.
6868 static expression_t *parse_cast(void)
6870 add_anchor_token(')');
6872 source_position_t source_position = token.source_position;
6874 type_t *type = parse_typename();
6876 rem_anchor_token(')');
6879 if (token.type == '{') {
6880 return parse_compound_literal(type);
6883 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6884 cast->base.source_position = source_position;
6886 expression_t *value = parse_sub_expression(PREC_CAST);
6887 cast->base.type = type;
6888 cast->unary.value = value;
6890 if (! semantic_cast(cast)) {
6891 /* TODO: record the error in the AST. else it is impossible to detect it */
6896 return create_invalid_expression();
6900 * Parse a statement expression.
6902 static expression_t *parse_statement_expression(void)
6904 add_anchor_token(')');
6906 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6908 statement_t *statement = parse_compound_statement(true);
6909 expression->statement.statement = statement;
6911 /* find last statement and use its type */
6912 type_t *type = type_void;
6913 const statement_t *stmt = statement->compound.statements;
6915 while (stmt->base.next != NULL)
6916 stmt = stmt->base.next;
6918 if (stmt->kind == STATEMENT_EXPRESSION) {
6919 type = stmt->expression.expression->base.type;
6921 } else if (warning.other) {
6922 warningf(&expression->base.source_position, "empty statement expression ({})");
6924 expression->base.type = type;
6926 rem_anchor_token(')');
6934 * Parse a parenthesized expression.
6936 static expression_t *parse_parenthesized_expression(void)
6940 switch (token.type) {
6942 /* gcc extension: a statement expression */
6943 return parse_statement_expression();
6947 return parse_cast();
6949 if (is_typedef_symbol(token.v.symbol)) {
6950 return parse_cast();
6954 add_anchor_token(')');
6955 expression_t *result = parse_expression();
6956 rem_anchor_token(')');
6963 static expression_t *parse_function_keyword(void)
6967 if (current_function == NULL) {
6968 errorf(HERE, "'__func__' used outside of a function");
6971 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6972 expression->base.type = type_char_ptr;
6973 expression->funcname.kind = FUNCNAME_FUNCTION;
6980 static expression_t *parse_pretty_function_keyword(void)
6982 if (current_function == NULL) {
6983 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6986 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6987 expression->base.type = type_char_ptr;
6988 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6990 eat(T___PRETTY_FUNCTION__);
6995 static expression_t *parse_funcsig_keyword(void)
6997 if (current_function == NULL) {
6998 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7001 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7002 expression->base.type = type_char_ptr;
7003 expression->funcname.kind = FUNCNAME_FUNCSIG;
7010 static expression_t *parse_funcdname_keyword(void)
7012 if (current_function == NULL) {
7013 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7016 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7017 expression->base.type = type_char_ptr;
7018 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7020 eat(T___FUNCDNAME__);
7025 static designator_t *parse_designator(void)
7027 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7028 result->source_position = *HERE;
7030 if (token.type != T_IDENTIFIER) {
7031 parse_error_expected("while parsing member designator",
7032 T_IDENTIFIER, NULL);
7035 result->symbol = token.v.symbol;
7038 designator_t *last_designator = result;
7040 if (token.type == '.') {
7042 if (token.type != T_IDENTIFIER) {
7043 parse_error_expected("while parsing member designator",
7044 T_IDENTIFIER, NULL);
7047 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7048 designator->source_position = *HERE;
7049 designator->symbol = token.v.symbol;
7052 last_designator->next = designator;
7053 last_designator = designator;
7056 if (token.type == '[') {
7058 add_anchor_token(']');
7059 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7060 designator->source_position = *HERE;
7061 designator->array_index = parse_expression();
7062 rem_anchor_token(']');
7064 if (designator->array_index == NULL) {
7068 last_designator->next = designator;
7069 last_designator = designator;
7081 * Parse the __builtin_offsetof() expression.
7083 static expression_t *parse_offsetof(void)
7085 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7086 expression->base.type = type_size_t;
7088 eat(T___builtin_offsetof);
7091 add_anchor_token(',');
7092 type_t *type = parse_typename();
7093 rem_anchor_token(',');
7095 add_anchor_token(')');
7096 designator_t *designator = parse_designator();
7097 rem_anchor_token(')');
7100 expression->offsetofe.type = type;
7101 expression->offsetofe.designator = designator;
7104 memset(&path, 0, sizeof(path));
7105 path.top_type = type;
7106 path.path = NEW_ARR_F(type_path_entry_t, 0);
7108 descend_into_subtype(&path);
7110 if (!walk_designator(&path, designator, true)) {
7111 return create_invalid_expression();
7114 DEL_ARR_F(path.path);
7118 return create_invalid_expression();
7122 * Parses a _builtin_va_start() expression.
7124 static expression_t *parse_va_start(void)
7126 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7128 eat(T___builtin_va_start);
7131 add_anchor_token(',');
7132 expression->va_starte.ap = parse_assignment_expression();
7133 rem_anchor_token(',');
7135 expression_t *const expr = parse_assignment_expression();
7136 if (expr->kind == EXPR_REFERENCE) {
7137 entity_t *const entity = expr->reference.entity;
7138 if (entity->base.parent_scope != ¤t_function->parameters
7139 || entity->base.next != NULL
7140 || entity->kind != ENTITY_VARIABLE) {
7141 errorf(&expr->base.source_position,
7142 "second argument of 'va_start' must be last parameter of the current function");
7144 expression->va_starte.parameter = &entity->variable;
7151 return create_invalid_expression();
7155 * Parses a _builtin_va_arg() expression.
7157 static expression_t *parse_va_arg(void)
7159 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7161 eat(T___builtin_va_arg);
7164 expression->va_arge.ap = parse_assignment_expression();
7166 expression->base.type = parse_typename();
7171 return create_invalid_expression();
7174 static expression_t *parse_builtin_symbol(void)
7176 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7178 symbol_t *symbol = token.v.symbol;
7180 expression->builtin_symbol.symbol = symbol;
7183 type_t *type = get_builtin_symbol_type(symbol);
7184 type = automatic_type_conversion(type);
7186 expression->base.type = type;
7191 * Parses a __builtin_constant() expression.
7193 static expression_t *parse_builtin_constant(void)
7195 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7197 eat(T___builtin_constant_p);
7200 add_anchor_token(')');
7201 expression->builtin_constant.value = parse_assignment_expression();
7202 rem_anchor_token(')');
7204 expression->base.type = type_int;
7208 return create_invalid_expression();
7212 * Parses a __builtin_prefetch() expression.
7214 static expression_t *parse_builtin_prefetch(void)
7216 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7218 eat(T___builtin_prefetch);
7221 add_anchor_token(')');
7222 expression->builtin_prefetch.adr = parse_assignment_expression();
7223 if (token.type == ',') {
7225 expression->builtin_prefetch.rw = parse_assignment_expression();
7227 if (token.type == ',') {
7229 expression->builtin_prefetch.locality = parse_assignment_expression();
7231 rem_anchor_token(')');
7233 expression->base.type = type_void;
7237 return create_invalid_expression();
7241 * Parses a __builtin_is_*() compare expression.
7243 static expression_t *parse_compare_builtin(void)
7245 expression_t *expression;
7247 switch (token.type) {
7248 case T___builtin_isgreater:
7249 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7251 case T___builtin_isgreaterequal:
7252 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7254 case T___builtin_isless:
7255 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7257 case T___builtin_islessequal:
7258 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7260 case T___builtin_islessgreater:
7261 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7263 case T___builtin_isunordered:
7264 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7267 internal_errorf(HERE, "invalid compare builtin found");
7269 expression->base.source_position = *HERE;
7273 expression->binary.left = parse_assignment_expression();
7275 expression->binary.right = parse_assignment_expression();
7278 type_t *const orig_type_left = expression->binary.left->base.type;
7279 type_t *const orig_type_right = expression->binary.right->base.type;
7281 type_t *const type_left = skip_typeref(orig_type_left);
7282 type_t *const type_right = skip_typeref(orig_type_right);
7283 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7284 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7285 type_error_incompatible("invalid operands in comparison",
7286 &expression->base.source_position, orig_type_left, orig_type_right);
7289 semantic_comparison(&expression->binary);
7294 return create_invalid_expression();
7299 * Parses a __builtin_expect() expression.
7301 static expression_t *parse_builtin_expect(void)
7303 expression_t *expression
7304 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7306 eat(T___builtin_expect);
7309 expression->binary.left = parse_assignment_expression();
7311 expression->binary.right = parse_constant_expression();
7314 expression->base.type = expression->binary.left->base.type;
7318 return create_invalid_expression();
7323 * Parses a MS assume() expression.
7325 static expression_t *parse_assume(void)
7327 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7332 add_anchor_token(')');
7333 expression->unary.value = parse_assignment_expression();
7334 rem_anchor_token(')');
7337 expression->base.type = type_void;
7340 return create_invalid_expression();
7344 * Return the declaration for a given label symbol or create a new one.
7346 * @param symbol the symbol of the label
7348 static label_t *get_label(symbol_t *symbol)
7351 assert(current_function != NULL);
7353 label = get_entity(symbol, NAMESPACE_LABEL);
7354 /* if we found a local label, we already created the declaration */
7355 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7356 if (label->base.parent_scope != current_scope) {
7357 assert(label->base.parent_scope->depth < current_scope->depth);
7358 current_function->goto_to_outer = true;
7360 return &label->label;
7363 label = get_entity(symbol, NAMESPACE_LABEL);
7364 /* if we found a label in the same function, then we already created the
7367 && label->base.parent_scope == ¤t_function->parameters) {
7368 return &label->label;
7371 /* otherwise we need to create a new one */
7372 label = allocate_entity_zero(ENTITY_LABEL);
7373 label->base.namespc = NAMESPACE_LABEL;
7374 label->base.symbol = symbol;
7378 return &label->label;
7382 * Parses a GNU && label address expression.
7384 static expression_t *parse_label_address(void)
7386 source_position_t source_position = token.source_position;
7388 if (token.type != T_IDENTIFIER) {
7389 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7392 symbol_t *symbol = token.v.symbol;
7395 label_t *label = get_label(symbol);
7397 label->address_taken = true;
7399 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7400 expression->base.source_position = source_position;
7402 /* label address is threaten as a void pointer */
7403 expression->base.type = type_void_ptr;
7404 expression->label_address.label = label;
7407 return create_invalid_expression();
7411 * Parse a microsoft __noop expression.
7413 static expression_t *parse_noop_expression(void)
7415 /* the result is a (int)0 */
7416 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7417 cnst->base.type = type_int;
7418 cnst->conste.v.int_value = 0;
7419 cnst->conste.is_ms_noop = true;
7423 if (token.type == '(') {
7424 /* parse arguments */
7426 add_anchor_token(')');
7427 add_anchor_token(',');
7429 if (token.type != ')') {
7431 (void)parse_assignment_expression();
7432 if (token.type != ',')
7438 rem_anchor_token(',');
7439 rem_anchor_token(')');
7447 * Parses a primary expression.
7449 static expression_t *parse_primary_expression(void)
7451 switch (token.type) {
7452 case T_false: return parse_bool_const(false);
7453 case T_true: return parse_bool_const(true);
7454 case T_INTEGER: return parse_int_const();
7455 case T_CHARACTER_CONSTANT: return parse_character_constant();
7456 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7457 case T_FLOATINGPOINT: return parse_float_const();
7458 case T_STRING_LITERAL:
7459 case T_WIDE_STRING_LITERAL: return parse_string_const();
7460 case T_IDENTIFIER: return parse_reference();
7461 case T___FUNCTION__:
7462 case T___func__: return parse_function_keyword();
7463 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7464 case T___FUNCSIG__: return parse_funcsig_keyword();
7465 case T___FUNCDNAME__: return parse_funcdname_keyword();
7466 case T___builtin_offsetof: return parse_offsetof();
7467 case T___builtin_va_start: return parse_va_start();
7468 case T___builtin_va_arg: return parse_va_arg();
7469 case T___builtin_expect:
7470 case T___builtin_alloca:
7471 case T___builtin_inf:
7472 case T___builtin_inff:
7473 case T___builtin_infl:
7474 case T___builtin_nan:
7475 case T___builtin_nanf:
7476 case T___builtin_nanl:
7477 case T___builtin_huge_val:
7478 case T___builtin_va_end: return parse_builtin_symbol();
7479 case T___builtin_isgreater:
7480 case T___builtin_isgreaterequal:
7481 case T___builtin_isless:
7482 case T___builtin_islessequal:
7483 case T___builtin_islessgreater:
7484 case T___builtin_isunordered: return parse_compare_builtin();
7485 case T___builtin_constant_p: return parse_builtin_constant();
7486 case T___builtin_prefetch: return parse_builtin_prefetch();
7487 case T__assume: return parse_assume();
7490 return parse_label_address();
7493 case '(': return parse_parenthesized_expression();
7494 case T___noop: return parse_noop_expression();
7497 errorf(HERE, "unexpected token %K, expected an expression", &token);
7498 return create_invalid_expression();
7502 * Check if the expression has the character type and issue a warning then.
7504 static void check_for_char_index_type(const expression_t *expression)
7506 type_t *const type = expression->base.type;
7507 const type_t *const base_type = skip_typeref(type);
7509 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7510 warning.char_subscripts) {
7511 warningf(&expression->base.source_position,
7512 "array subscript has type '%T'", type);
7516 static expression_t *parse_array_expression(expression_t *left)
7518 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7521 add_anchor_token(']');
7523 expression_t *inside = parse_expression();
7525 type_t *const orig_type_left = left->base.type;
7526 type_t *const orig_type_inside = inside->base.type;
7528 type_t *const type_left = skip_typeref(orig_type_left);
7529 type_t *const type_inside = skip_typeref(orig_type_inside);
7531 type_t *return_type;
7532 array_access_expression_t *array_access = &expression->array_access;
7533 if (is_type_pointer(type_left)) {
7534 return_type = type_left->pointer.points_to;
7535 array_access->array_ref = left;
7536 array_access->index = inside;
7537 check_for_char_index_type(inside);
7538 } else if (is_type_pointer(type_inside)) {
7539 return_type = type_inside->pointer.points_to;
7540 array_access->array_ref = inside;
7541 array_access->index = left;
7542 array_access->flipped = true;
7543 check_for_char_index_type(left);
7545 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7547 "array access on object with non-pointer types '%T', '%T'",
7548 orig_type_left, orig_type_inside);
7550 return_type = type_error_type;
7551 array_access->array_ref = left;
7552 array_access->index = inside;
7555 expression->base.type = automatic_type_conversion(return_type);
7557 rem_anchor_token(']');
7563 static expression_t *parse_typeprop(expression_kind_t const kind)
7565 expression_t *tp_expression = allocate_expression_zero(kind);
7566 tp_expression->base.type = type_size_t;
7568 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7570 /* we only refer to a type property, mark this case */
7571 bool old = in_type_prop;
7572 in_type_prop = true;
7575 expression_t *expression;
7576 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7578 add_anchor_token(')');
7579 orig_type = parse_typename();
7580 rem_anchor_token(')');
7583 if (token.type == '{') {
7584 /* It was not sizeof(type) after all. It is sizeof of an expression
7585 * starting with a compound literal */
7586 expression = parse_compound_literal(orig_type);
7587 goto typeprop_expression;
7590 expression = parse_sub_expression(PREC_UNARY);
7592 typeprop_expression:
7593 tp_expression->typeprop.tp_expression = expression;
7595 orig_type = revert_automatic_type_conversion(expression);
7596 expression->base.type = orig_type;
7599 tp_expression->typeprop.type = orig_type;
7600 type_t const* const type = skip_typeref(orig_type);
7601 char const* const wrong_type =
7602 is_type_incomplete(type) ? "incomplete" :
7603 type->kind == TYPE_FUNCTION ? "function designator" :
7604 type->kind == TYPE_BITFIELD ? "bitfield" :
7606 if (wrong_type != NULL) {
7607 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7608 errorf(&tp_expression->base.source_position,
7609 "operand of %s expression must not be of %s type '%T'",
7610 what, wrong_type, orig_type);
7615 return tp_expression;
7618 static expression_t *parse_sizeof(void)
7620 return parse_typeprop(EXPR_SIZEOF);
7623 static expression_t *parse_alignof(void)
7625 return parse_typeprop(EXPR_ALIGNOF);
7628 static expression_t *parse_select_expression(expression_t *compound)
7630 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7631 select->select.compound = compound;
7633 assert(token.type == '.' || token.type == T_MINUSGREATER);
7634 bool is_pointer = (token.type == T_MINUSGREATER);
7637 if (token.type != T_IDENTIFIER) {
7638 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7641 symbol_t *symbol = token.v.symbol;
7644 type_t *const orig_type = compound->base.type;
7645 type_t *const type = skip_typeref(orig_type);
7648 bool saw_error = false;
7649 if (is_type_pointer(type)) {
7652 "request for member '%Y' in something not a struct or union, but '%T'",
7656 type_left = skip_typeref(type->pointer.points_to);
7658 if (is_pointer && is_type_valid(type)) {
7659 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7666 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7667 type_left->kind == TYPE_COMPOUND_UNION) {
7668 compound_t *compound = type_left->compound.compound;
7670 if (!compound->complete) {
7671 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7673 goto create_error_entry;
7676 entry = find_compound_entry(compound, symbol);
7677 if (entry == NULL) {
7678 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7679 goto create_error_entry;
7682 if (is_type_valid(type_left) && !saw_error) {
7684 "request for member '%Y' in something not a struct or union, but '%T'",
7688 return create_invalid_expression();
7691 assert(is_declaration(entry));
7692 select->select.compound_entry = entry;
7694 type_t *entry_type = entry->declaration.type;
7696 = get_qualified_type(entry_type, type_left->base.qualifiers);
7698 /* we always do the auto-type conversions; the & and sizeof parser contains
7699 * code to revert this! */
7700 select->base.type = automatic_type_conversion(res_type);
7702 type_t *skipped = skip_typeref(res_type);
7703 if (skipped->kind == TYPE_BITFIELD) {
7704 select->base.type = skipped->bitfield.base_type;
7710 static void check_call_argument(const function_parameter_t *parameter,
7711 call_argument_t *argument, unsigned pos)
7713 type_t *expected_type = parameter->type;
7714 type_t *expected_type_skip = skip_typeref(expected_type);
7715 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7716 expression_t *arg_expr = argument->expression;
7717 type_t *arg_type = skip_typeref(arg_expr->base.type);
7719 /* handle transparent union gnu extension */
7720 if (is_type_union(expected_type_skip)
7721 && (expected_type_skip->base.modifiers
7722 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7723 compound_t *union_decl = expected_type_skip->compound.compound;
7724 type_t *best_type = NULL;
7725 entity_t *entry = union_decl->members.entities;
7726 for ( ; entry != NULL; entry = entry->base.next) {
7727 assert(is_declaration(entry));
7728 type_t *decl_type = entry->declaration.type;
7729 error = semantic_assign(decl_type, arg_expr);
7730 if (error == ASSIGN_ERROR_INCOMPATIBLE
7731 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7734 if (error == ASSIGN_SUCCESS) {
7735 best_type = decl_type;
7736 } else if (best_type == NULL) {
7737 best_type = decl_type;
7741 if (best_type != NULL) {
7742 expected_type = best_type;
7746 error = semantic_assign(expected_type, arg_expr);
7747 argument->expression = create_implicit_cast(argument->expression,
7750 if (error != ASSIGN_SUCCESS) {
7751 /* report exact scope in error messages (like "in argument 3") */
7753 snprintf(buf, sizeof(buf), "call argument %u", pos);
7754 report_assign_error(error, expected_type, arg_expr, buf,
7755 &arg_expr->base.source_position);
7756 } else if (warning.traditional || warning.conversion) {
7757 type_t *const promoted_type = get_default_promoted_type(arg_type);
7758 if (!types_compatible(expected_type_skip, promoted_type) &&
7759 !types_compatible(expected_type_skip, type_void_ptr) &&
7760 !types_compatible(type_void_ptr, promoted_type)) {
7761 /* Deliberately show the skipped types in this warning */
7762 warningf(&arg_expr->base.source_position,
7763 "passing call argument %u as '%T' rather than '%T' due to prototype",
7764 pos, expected_type_skip, promoted_type);
7770 * Parse a call expression, ie. expression '( ... )'.
7772 * @param expression the function address
7774 static expression_t *parse_call_expression(expression_t *expression)
7776 expression_t *result = allocate_expression_zero(EXPR_CALL);
7777 call_expression_t *call = &result->call;
7778 call->function = expression;
7780 type_t *const orig_type = expression->base.type;
7781 type_t *const type = skip_typeref(orig_type);
7783 function_type_t *function_type = NULL;
7784 if (is_type_pointer(type)) {
7785 type_t *const to_type = skip_typeref(type->pointer.points_to);
7787 if (is_type_function(to_type)) {
7788 function_type = &to_type->function;
7789 call->base.type = function_type->return_type;
7793 if (function_type == NULL && is_type_valid(type)) {
7794 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7797 /* parse arguments */
7799 add_anchor_token(')');
7800 add_anchor_token(',');
7802 if (token.type != ')') {
7803 call_argument_t *last_argument = NULL;
7806 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7808 argument->expression = parse_assignment_expression();
7809 if (last_argument == NULL) {
7810 call->arguments = argument;
7812 last_argument->next = argument;
7814 last_argument = argument;
7816 if (token.type != ',')
7821 rem_anchor_token(',');
7822 rem_anchor_token(')');
7825 if (function_type == NULL)
7828 function_parameter_t *parameter = function_type->parameters;
7829 call_argument_t *argument = call->arguments;
7830 if (!function_type->unspecified_parameters) {
7831 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7832 parameter = parameter->next, argument = argument->next) {
7833 check_call_argument(parameter, argument, ++pos);
7836 if (parameter != NULL) {
7837 errorf(HERE, "too few arguments to function '%E'", expression);
7838 } else if (argument != NULL && !function_type->variadic) {
7839 errorf(HERE, "too many arguments to function '%E'", expression);
7843 /* do default promotion */
7844 for (; argument != NULL; argument = argument->next) {
7845 type_t *type = argument->expression->base.type;
7847 type = get_default_promoted_type(type);
7849 argument->expression
7850 = create_implicit_cast(argument->expression, type);
7853 check_format(&result->call);
7855 if (warning.aggregate_return &&
7856 is_type_compound(skip_typeref(function_type->return_type))) {
7857 warningf(&result->base.source_position,
7858 "function call has aggregate value");
7865 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7867 static bool same_compound_type(const type_t *type1, const type_t *type2)
7870 is_type_compound(type1) &&
7871 type1->kind == type2->kind &&
7872 type1->compound.compound == type2->compound.compound;
7875 static expression_t const *get_reference_address(expression_t const *expr)
7877 bool regular_take_address = true;
7879 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7880 expr = expr->unary.value;
7882 regular_take_address = false;
7885 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7888 expr = expr->unary.value;
7891 if (expr->kind != EXPR_REFERENCE)
7894 /* special case for functions which are automatically converted to a
7895 * pointer to function without an extra TAKE_ADDRESS operation */
7896 if (!regular_take_address &&
7897 expr->reference.entity->kind != ENTITY_FUNCTION) {
7904 static void warn_reference_address_as_bool(expression_t const* expr)
7906 if (!warning.address)
7909 expr = get_reference_address(expr);
7911 warningf(&expr->base.source_position,
7912 "the address of '%Y' will always evaluate as 'true'",
7913 expr->reference.entity->base.symbol);
7917 static void semantic_condition(expression_t const *const expr,
7918 char const *const context)
7920 type_t *const type = skip_typeref(expr->base.type);
7921 if (is_type_scalar(type)) {
7922 warn_reference_address_as_bool(expr);
7923 } else if (is_type_valid(type)) {
7924 errorf(&expr->base.source_position,
7925 "%s must have scalar type", context);
7930 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7932 * @param expression the conditional expression
7934 static expression_t *parse_conditional_expression(expression_t *expression)
7936 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7938 conditional_expression_t *conditional = &result->conditional;
7939 conditional->condition = expression;
7942 add_anchor_token(':');
7944 /* §6.5.15:2 The first operand shall have scalar type. */
7945 semantic_condition(expression, "condition of conditional operator");
7947 expression_t *true_expression = expression;
7948 bool gnu_cond = false;
7949 if (GNU_MODE && token.type == ':') {
7952 true_expression = parse_expression();
7954 rem_anchor_token(':');
7956 expression_t *false_expression =
7957 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7959 type_t *const orig_true_type = true_expression->base.type;
7960 type_t *const orig_false_type = false_expression->base.type;
7961 type_t *const true_type = skip_typeref(orig_true_type);
7962 type_t *const false_type = skip_typeref(orig_false_type);
7965 type_t *result_type;
7966 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7967 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7968 /* ISO/IEC 14882:1998(E) §5.16:2 */
7969 if (true_expression->kind == EXPR_UNARY_THROW) {
7970 result_type = false_type;
7971 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7972 result_type = true_type;
7974 if (warning.other && (
7975 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7976 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7978 warningf(&conditional->base.source_position,
7979 "ISO C forbids conditional expression with only one void side");
7981 result_type = type_void;
7983 } else if (is_type_arithmetic(true_type)
7984 && is_type_arithmetic(false_type)) {
7985 result_type = semantic_arithmetic(true_type, false_type);
7987 true_expression = create_implicit_cast(true_expression, result_type);
7988 false_expression = create_implicit_cast(false_expression, result_type);
7990 conditional->true_expression = true_expression;
7991 conditional->false_expression = false_expression;
7992 conditional->base.type = result_type;
7993 } else if (same_compound_type(true_type, false_type)) {
7994 /* just take 1 of the 2 types */
7995 result_type = true_type;
7996 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7997 type_t *pointer_type;
7999 expression_t *other_expression;
8000 if (is_type_pointer(true_type) &&
8001 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8002 pointer_type = true_type;
8003 other_type = false_type;
8004 other_expression = false_expression;
8006 pointer_type = false_type;
8007 other_type = true_type;
8008 other_expression = true_expression;
8011 if (is_null_pointer_constant(other_expression)) {
8012 result_type = pointer_type;
8013 } else if (is_type_pointer(other_type)) {
8014 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8015 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8018 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8019 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8021 } else if (types_compatible(get_unqualified_type(to1),
8022 get_unqualified_type(to2))) {
8025 if (warning.other) {
8026 warningf(&conditional->base.source_position,
8027 "pointer types '%T' and '%T' in conditional expression are incompatible",
8028 true_type, false_type);
8033 type_t *const type =
8034 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8035 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8036 } else if (is_type_integer(other_type)) {
8037 if (warning.other) {
8038 warningf(&conditional->base.source_position,
8039 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8041 result_type = pointer_type;
8043 if (is_type_valid(other_type)) {
8044 type_error_incompatible("while parsing conditional",
8045 &expression->base.source_position, true_type, false_type);
8047 result_type = type_error_type;
8050 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8051 type_error_incompatible("while parsing conditional",
8052 &conditional->base.source_position, true_type,
8055 result_type = type_error_type;
8058 conditional->true_expression
8059 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8060 conditional->false_expression
8061 = create_implicit_cast(false_expression, result_type);
8062 conditional->base.type = result_type;
8065 return create_invalid_expression();
8069 * Parse an extension expression.
8071 static expression_t *parse_extension(void)
8073 eat(T___extension__);
8075 bool old_gcc_extension = in_gcc_extension;
8076 in_gcc_extension = true;
8077 expression_t *expression = parse_sub_expression(PREC_UNARY);
8078 in_gcc_extension = old_gcc_extension;
8083 * Parse a __builtin_classify_type() expression.
8085 static expression_t *parse_builtin_classify_type(void)
8087 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8088 result->base.type = type_int;
8090 eat(T___builtin_classify_type);
8093 add_anchor_token(')');
8094 expression_t *expression = parse_expression();
8095 rem_anchor_token(')');
8097 result->classify_type.type_expression = expression;
8101 return create_invalid_expression();
8105 * Parse a delete expression
8106 * ISO/IEC 14882:1998(E) §5.3.5
8108 static expression_t *parse_delete(void)
8110 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8111 result->base.type = type_void;
8115 if (token.type == '[') {
8117 result->kind = EXPR_UNARY_DELETE_ARRAY;
8122 expression_t *const value = parse_sub_expression(PREC_CAST);
8123 result->unary.value = value;
8125 type_t *const type = skip_typeref(value->base.type);
8126 if (!is_type_pointer(type)) {
8127 errorf(&value->base.source_position,
8128 "operand of delete must have pointer type");
8129 } else if (warning.other &&
8130 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8131 warningf(&value->base.source_position,
8132 "deleting 'void*' is undefined");
8139 * Parse a throw expression
8140 * ISO/IEC 14882:1998(E) §15:1
8142 static expression_t *parse_throw(void)
8144 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8145 result->base.type = type_void;
8149 expression_t *value = NULL;
8150 switch (token.type) {
8152 value = parse_assignment_expression();
8153 /* ISO/IEC 14882:1998(E) §15.1:3 */
8154 type_t *const orig_type = value->base.type;
8155 type_t *const type = skip_typeref(orig_type);
8156 if (is_type_incomplete(type)) {
8157 errorf(&value->base.source_position,
8158 "cannot throw object of incomplete type '%T'", orig_type);
8159 } else if (is_type_pointer(type)) {
8160 type_t *const points_to = skip_typeref(type->pointer.points_to);
8161 if (is_type_incomplete(points_to) &&
8162 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8163 errorf(&value->base.source_position,
8164 "cannot throw pointer to incomplete type '%T'", orig_type);
8172 result->unary.value = value;
8177 static bool check_pointer_arithmetic(const source_position_t *source_position,
8178 type_t *pointer_type,
8179 type_t *orig_pointer_type)
8181 type_t *points_to = pointer_type->pointer.points_to;
8182 points_to = skip_typeref(points_to);
8184 if (is_type_incomplete(points_to)) {
8185 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8186 errorf(source_position,
8187 "arithmetic with pointer to incomplete type '%T' not allowed",
8190 } else if (warning.pointer_arith) {
8191 warningf(source_position,
8192 "pointer of type '%T' used in arithmetic",
8195 } else if (is_type_function(points_to)) {
8197 errorf(source_position,
8198 "arithmetic with pointer to function type '%T' not allowed",
8201 } else if (warning.pointer_arith) {
8202 warningf(source_position,
8203 "pointer to a function '%T' used in arithmetic",
8210 static bool is_lvalue(const expression_t *expression)
8212 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8213 switch (expression->kind) {
8214 case EXPR_REFERENCE:
8215 case EXPR_ARRAY_ACCESS:
8217 case EXPR_UNARY_DEREFERENCE:
8221 /* Claim it is an lvalue, if the type is invalid. There was a parse
8222 * error before, which maybe prevented properly recognizing it as
8224 return !is_type_valid(skip_typeref(expression->base.type));
8228 static void semantic_incdec(unary_expression_t *expression)
8230 type_t *const orig_type = expression->value->base.type;
8231 type_t *const type = skip_typeref(orig_type);
8232 if (is_type_pointer(type)) {
8233 if (!check_pointer_arithmetic(&expression->base.source_position,
8237 } else if (!is_type_real(type) && is_type_valid(type)) {
8238 /* TODO: improve error message */
8239 errorf(&expression->base.source_position,
8240 "operation needs an arithmetic or pointer type");
8243 if (!is_lvalue(expression->value)) {
8244 /* TODO: improve error message */
8245 errorf(&expression->base.source_position, "lvalue required as operand");
8247 expression->base.type = orig_type;
8250 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8252 type_t *const orig_type = expression->value->base.type;
8253 type_t *const type = skip_typeref(orig_type);
8254 if (!is_type_arithmetic(type)) {
8255 if (is_type_valid(type)) {
8256 /* TODO: improve error message */
8257 errorf(&expression->base.source_position,
8258 "operation needs an arithmetic type");
8263 expression->base.type = orig_type;
8266 static void semantic_unexpr_plus(unary_expression_t *expression)
8268 semantic_unexpr_arithmetic(expression);
8269 if (warning.traditional)
8270 warningf(&expression->base.source_position,
8271 "traditional C rejects the unary plus operator");
8274 static void semantic_not(unary_expression_t *expression)
8276 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8277 semantic_condition(expression->value, "operand of !");
8278 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8281 static void semantic_unexpr_integer(unary_expression_t *expression)
8283 type_t *const orig_type = expression->value->base.type;
8284 type_t *const type = skip_typeref(orig_type);
8285 if (!is_type_integer(type)) {
8286 if (is_type_valid(type)) {
8287 errorf(&expression->base.source_position,
8288 "operand of ~ must be of integer type");
8293 expression->base.type = orig_type;
8296 static void semantic_dereference(unary_expression_t *expression)
8298 type_t *const orig_type = expression->value->base.type;
8299 type_t *const type = skip_typeref(orig_type);
8300 if (!is_type_pointer(type)) {
8301 if (is_type_valid(type)) {
8302 errorf(&expression->base.source_position,
8303 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8308 type_t *result_type = type->pointer.points_to;
8309 result_type = automatic_type_conversion(result_type);
8310 expression->base.type = result_type;
8314 * Record that an address is taken (expression represents an lvalue).
8316 * @param expression the expression
8317 * @param may_be_register if true, the expression might be an register
8319 static void set_address_taken(expression_t *expression, bool may_be_register)
8321 if (expression->kind != EXPR_REFERENCE)
8324 entity_t *const entity = expression->reference.entity;
8326 if (entity->kind != ENTITY_VARIABLE)
8329 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8330 && !may_be_register) {
8331 errorf(&expression->base.source_position,
8332 "address of register variable '%Y' requested",
8333 entity->base.symbol);
8336 entity->variable.address_taken = true;
8340 * Check the semantic of the address taken expression.
8342 static void semantic_take_addr(unary_expression_t *expression)
8344 expression_t *value = expression->value;
8345 value->base.type = revert_automatic_type_conversion(value);
8347 type_t *orig_type = value->base.type;
8348 type_t *type = skip_typeref(orig_type);
8349 if (!is_type_valid(type))
8353 if (!is_lvalue(value)) {
8354 errorf(&expression->base.source_position, "'&' requires an lvalue");
8356 if (type->kind == TYPE_BITFIELD) {
8357 errorf(&expression->base.source_position,
8358 "'&' not allowed on object with bitfield type '%T'",
8362 set_address_taken(value, false);
8364 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8367 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8368 static expression_t *parse_##unexpression_type(void) \
8370 expression_t *unary_expression \
8371 = allocate_expression_zero(unexpression_type); \
8373 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8375 sfunc(&unary_expression->unary); \
8377 return unary_expression; \
8380 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8381 semantic_unexpr_arithmetic)
8382 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8383 semantic_unexpr_plus)
8384 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8386 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8387 semantic_dereference)
8388 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8390 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8391 semantic_unexpr_integer)
8392 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8394 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8397 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8399 static expression_t *parse_##unexpression_type(expression_t *left) \
8401 expression_t *unary_expression \
8402 = allocate_expression_zero(unexpression_type); \
8404 unary_expression->unary.value = left; \
8406 sfunc(&unary_expression->unary); \
8408 return unary_expression; \
8411 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8412 EXPR_UNARY_POSTFIX_INCREMENT,
8414 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8415 EXPR_UNARY_POSTFIX_DECREMENT,
8418 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8420 /* TODO: handle complex + imaginary types */
8422 type_left = get_unqualified_type(type_left);
8423 type_right = get_unqualified_type(type_right);
8425 /* § 6.3.1.8 Usual arithmetic conversions */
8426 if (type_left == type_long_double || type_right == type_long_double) {
8427 return type_long_double;
8428 } else if (type_left == type_double || type_right == type_double) {
8430 } else if (type_left == type_float || type_right == type_float) {
8434 type_left = promote_integer(type_left);
8435 type_right = promote_integer(type_right);
8437 if (type_left == type_right)
8440 bool const signed_left = is_type_signed(type_left);
8441 bool const signed_right = is_type_signed(type_right);
8442 int const rank_left = get_rank(type_left);
8443 int const rank_right = get_rank(type_right);
8445 if (signed_left == signed_right)
8446 return rank_left >= rank_right ? type_left : type_right;
8455 u_rank = rank_right;
8456 u_type = type_right;
8458 s_rank = rank_right;
8459 s_type = type_right;
8464 if (u_rank >= s_rank)
8467 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8469 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8470 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8474 case ATOMIC_TYPE_INT: return type_unsigned_int;
8475 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8476 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8478 default: panic("invalid atomic type");
8483 * Check the semantic restrictions for a binary expression.
8485 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8487 expression_t *const left = expression->left;
8488 expression_t *const right = expression->right;
8489 type_t *const orig_type_left = left->base.type;
8490 type_t *const orig_type_right = right->base.type;
8491 type_t *const type_left = skip_typeref(orig_type_left);
8492 type_t *const type_right = skip_typeref(orig_type_right);
8494 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8495 /* TODO: improve error message */
8496 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8497 errorf(&expression->base.source_position,
8498 "operation needs arithmetic types");
8503 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8504 expression->left = create_implicit_cast(left, arithmetic_type);
8505 expression->right = create_implicit_cast(right, arithmetic_type);
8506 expression->base.type = arithmetic_type;
8509 static void warn_div_by_zero(binary_expression_t const *const expression)
8511 if (!warning.div_by_zero ||
8512 !is_type_integer(expression->base.type))
8515 expression_t const *const right = expression->right;
8516 /* The type of the right operand can be different for /= */
8517 if (is_type_integer(right->base.type) &&
8518 is_constant_expression(right) &&
8519 fold_constant(right) == 0) {
8520 warningf(&expression->base.source_position, "division by zero");
8525 * Check the semantic restrictions for a div/mod expression.
8527 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8528 semantic_binexpr_arithmetic(expression);
8529 warn_div_by_zero(expression);
8532 static void semantic_shift_op(binary_expression_t *expression)
8534 expression_t *const left = expression->left;
8535 expression_t *const right = expression->right;
8536 type_t *const orig_type_left = left->base.type;
8537 type_t *const orig_type_right = right->base.type;
8538 type_t * type_left = skip_typeref(orig_type_left);
8539 type_t * type_right = skip_typeref(orig_type_right);
8541 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8542 /* TODO: improve error message */
8543 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8544 errorf(&expression->base.source_position,
8545 "operands of shift operation must have integer types");
8550 type_left = promote_integer(type_left);
8551 type_right = promote_integer(type_right);
8553 expression->left = create_implicit_cast(left, type_left);
8554 expression->right = create_implicit_cast(right, type_right);
8555 expression->base.type = type_left;
8558 static void semantic_add(binary_expression_t *expression)
8560 expression_t *const left = expression->left;
8561 expression_t *const right = expression->right;
8562 type_t *const orig_type_left = left->base.type;
8563 type_t *const orig_type_right = right->base.type;
8564 type_t *const type_left = skip_typeref(orig_type_left);
8565 type_t *const type_right = skip_typeref(orig_type_right);
8568 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8569 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8570 expression->left = create_implicit_cast(left, arithmetic_type);
8571 expression->right = create_implicit_cast(right, arithmetic_type);
8572 expression->base.type = arithmetic_type;
8574 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8575 check_pointer_arithmetic(&expression->base.source_position,
8576 type_left, orig_type_left);
8577 expression->base.type = type_left;
8578 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8579 check_pointer_arithmetic(&expression->base.source_position,
8580 type_right, orig_type_right);
8581 expression->base.type = type_right;
8582 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8583 errorf(&expression->base.source_position,
8584 "invalid operands to binary + ('%T', '%T')",
8585 orig_type_left, orig_type_right);
8589 static void semantic_sub(binary_expression_t *expression)
8591 expression_t *const left = expression->left;
8592 expression_t *const right = expression->right;
8593 type_t *const orig_type_left = left->base.type;
8594 type_t *const orig_type_right = right->base.type;
8595 type_t *const type_left = skip_typeref(orig_type_left);
8596 type_t *const type_right = skip_typeref(orig_type_right);
8597 source_position_t const *const pos = &expression->base.source_position;
8600 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8601 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8602 expression->left = create_implicit_cast(left, arithmetic_type);
8603 expression->right = create_implicit_cast(right, arithmetic_type);
8604 expression->base.type = arithmetic_type;
8606 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8607 check_pointer_arithmetic(&expression->base.source_position,
8608 type_left, orig_type_left);
8609 expression->base.type = type_left;
8610 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8611 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8612 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8613 if (!types_compatible(unqual_left, unqual_right)) {
8615 "subtracting pointers to incompatible types '%T' and '%T'",
8616 orig_type_left, orig_type_right);
8617 } else if (!is_type_object(unqual_left)) {
8618 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8619 errorf(pos, "subtracting pointers to non-object types '%T'",
8621 } else if (warning.other) {
8622 warningf(pos, "subtracting pointers to void");
8625 expression->base.type = type_ptrdiff_t;
8626 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8627 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8628 orig_type_left, orig_type_right);
8632 static void warn_string_literal_address(expression_t const* expr)
8634 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8635 expr = expr->unary.value;
8636 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8638 expr = expr->unary.value;
8641 if (expr->kind == EXPR_STRING_LITERAL ||
8642 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8643 warningf(&expr->base.source_position,
8644 "comparison with string literal results in unspecified behaviour");
8649 * Check the semantics of comparison expressions.
8651 * @param expression The expression to check.
8653 static void semantic_comparison(binary_expression_t *expression)
8655 expression_t *left = expression->left;
8656 expression_t *right = expression->right;
8658 if (warning.address) {
8659 warn_string_literal_address(left);
8660 warn_string_literal_address(right);
8662 expression_t const* const func_left = get_reference_address(left);
8663 if (func_left != NULL && is_null_pointer_constant(right)) {
8664 warningf(&expression->base.source_position,
8665 "the address of '%Y' will never be NULL",
8666 func_left->reference.entity->base.symbol);
8669 expression_t const* const func_right = get_reference_address(right);
8670 if (func_right != NULL && is_null_pointer_constant(right)) {
8671 warningf(&expression->base.source_position,
8672 "the address of '%Y' will never be NULL",
8673 func_right->reference.entity->base.symbol);
8677 type_t *orig_type_left = left->base.type;
8678 type_t *orig_type_right = right->base.type;
8679 type_t *type_left = skip_typeref(orig_type_left);
8680 type_t *type_right = skip_typeref(orig_type_right);
8682 /* TODO non-arithmetic types */
8683 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8684 /* test for signed vs unsigned compares */
8685 if (warning.sign_compare &&
8686 (expression->base.kind != EXPR_BINARY_EQUAL &&
8687 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8688 (is_type_signed(type_left) != is_type_signed(type_right))) {
8690 /* check if 1 of the operands is a constant, in this case we just
8691 * check wether we can safely represent the resulting constant in
8692 * the type of the other operand. */
8693 expression_t *const_expr = NULL;
8694 expression_t *other_expr = NULL;
8696 if (is_constant_expression(left)) {
8699 } else if (is_constant_expression(right)) {
8704 if (const_expr != NULL) {
8705 type_t *other_type = skip_typeref(other_expr->base.type);
8706 long val = fold_constant(const_expr);
8707 /* TODO: check if val can be represented by other_type */
8711 warningf(&expression->base.source_position,
8712 "comparison between signed and unsigned");
8714 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8715 expression->left = create_implicit_cast(left, arithmetic_type);
8716 expression->right = create_implicit_cast(right, arithmetic_type);
8717 expression->base.type = arithmetic_type;
8718 if (warning.float_equal &&
8719 (expression->base.kind == EXPR_BINARY_EQUAL ||
8720 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8721 is_type_float(arithmetic_type)) {
8722 warningf(&expression->base.source_position,
8723 "comparing floating point with == or != is unsafe");
8725 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8726 /* TODO check compatibility */
8727 } else if (is_type_pointer(type_left)) {
8728 expression->right = create_implicit_cast(right, type_left);
8729 } else if (is_type_pointer(type_right)) {
8730 expression->left = create_implicit_cast(left, type_right);
8731 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8732 type_error_incompatible("invalid operands in comparison",
8733 &expression->base.source_position,
8734 type_left, type_right);
8736 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8740 * Checks if a compound type has constant fields.
8742 static bool has_const_fields(const compound_type_t *type)
8744 compound_t *compound = type->compound;
8745 entity_t *entry = compound->members.entities;
8747 for (; entry != NULL; entry = entry->base.next) {
8748 if (!is_declaration(entry))
8751 const type_t *decl_type = skip_typeref(entry->declaration.type);
8752 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8759 static bool is_valid_assignment_lhs(expression_t const* const left)
8761 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8762 type_t *const type_left = skip_typeref(orig_type_left);
8764 if (!is_lvalue(left)) {
8765 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8770 if (is_type_array(type_left)) {
8771 errorf(HERE, "cannot assign to arrays ('%E')", left);
8774 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8775 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8779 if (is_type_incomplete(type_left)) {
8780 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8781 left, orig_type_left);
8784 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8785 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8786 left, orig_type_left);
8793 static void semantic_arithmetic_assign(binary_expression_t *expression)
8795 expression_t *left = expression->left;
8796 expression_t *right = expression->right;
8797 type_t *orig_type_left = left->base.type;
8798 type_t *orig_type_right = right->base.type;
8800 if (!is_valid_assignment_lhs(left))
8803 type_t *type_left = skip_typeref(orig_type_left);
8804 type_t *type_right = skip_typeref(orig_type_right);
8806 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8807 /* TODO: improve error message */
8808 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8809 errorf(&expression->base.source_position,
8810 "operation needs arithmetic types");
8815 /* combined instructions are tricky. We can't create an implicit cast on
8816 * the left side, because we need the uncasted form for the store.
8817 * The ast2firm pass has to know that left_type must be right_type
8818 * for the arithmetic operation and create a cast by itself */
8819 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8820 expression->right = create_implicit_cast(right, arithmetic_type);
8821 expression->base.type = type_left;
8824 static void semantic_divmod_assign(binary_expression_t *expression)
8826 semantic_arithmetic_assign(expression);
8827 warn_div_by_zero(expression);
8830 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8832 expression_t *const left = expression->left;
8833 expression_t *const right = expression->right;
8834 type_t *const orig_type_left = left->base.type;
8835 type_t *const orig_type_right = right->base.type;
8836 type_t *const type_left = skip_typeref(orig_type_left);
8837 type_t *const type_right = skip_typeref(orig_type_right);
8839 if (!is_valid_assignment_lhs(left))
8842 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8843 /* combined instructions are tricky. We can't create an implicit cast on
8844 * the left side, because we need the uncasted form for the store.
8845 * The ast2firm pass has to know that left_type must be right_type
8846 * for the arithmetic operation and create a cast by itself */
8847 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8848 expression->right = create_implicit_cast(right, arithmetic_type);
8849 expression->base.type = type_left;
8850 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8851 check_pointer_arithmetic(&expression->base.source_position,
8852 type_left, orig_type_left);
8853 expression->base.type = type_left;
8854 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8855 errorf(&expression->base.source_position,
8856 "incompatible types '%T' and '%T' in assignment",
8857 orig_type_left, orig_type_right);
8862 * Check the semantic restrictions of a logical expression.
8864 static void semantic_logical_op(binary_expression_t *expression)
8866 /* §6.5.13:2 Each of the operands shall have scalar type.
8867 * §6.5.14:2 Each of the operands shall have scalar type. */
8868 semantic_condition(expression->left, "left operand of logical operator");
8869 semantic_condition(expression->right, "right operand of logical operator");
8870 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8874 * Check the semantic restrictions of a binary assign expression.
8876 static void semantic_binexpr_assign(binary_expression_t *expression)
8878 expression_t *left = expression->left;
8879 type_t *orig_type_left = left->base.type;
8881 if (!is_valid_assignment_lhs(left))
8884 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8885 report_assign_error(error, orig_type_left, expression->right,
8886 "assignment", &left->base.source_position);
8887 expression->right = create_implicit_cast(expression->right, orig_type_left);
8888 expression->base.type = orig_type_left;
8892 * Determine if the outermost operation (or parts thereof) of the given
8893 * expression has no effect in order to generate a warning about this fact.
8894 * Therefore in some cases this only examines some of the operands of the
8895 * expression (see comments in the function and examples below).
8897 * f() + 23; // warning, because + has no effect
8898 * x || f(); // no warning, because x controls execution of f()
8899 * x ? y : f(); // warning, because y has no effect
8900 * (void)x; // no warning to be able to suppress the warning
8901 * This function can NOT be used for an "expression has definitely no effect"-
8903 static bool expression_has_effect(const expression_t *const expr)
8905 switch (expr->kind) {
8906 case EXPR_UNKNOWN: break;
8907 case EXPR_INVALID: return true; /* do NOT warn */
8908 case EXPR_REFERENCE: return false;
8909 case EXPR_REFERENCE_ENUM_VALUE: return false;
8910 /* suppress the warning for microsoft __noop operations */
8911 case EXPR_CONST: return expr->conste.is_ms_noop;
8912 case EXPR_CHARACTER_CONSTANT: return false;
8913 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8914 case EXPR_STRING_LITERAL: return false;
8915 case EXPR_WIDE_STRING_LITERAL: return false;
8916 case EXPR_LABEL_ADDRESS: return false;
8919 const call_expression_t *const call = &expr->call;
8920 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8923 switch (call->function->builtin_symbol.symbol->ID) {
8924 case T___builtin_va_end: return true;
8925 default: return false;
8929 /* Generate the warning if either the left or right hand side of a
8930 * conditional expression has no effect */
8931 case EXPR_CONDITIONAL: {
8932 const conditional_expression_t *const cond = &expr->conditional;
8934 expression_has_effect(cond->true_expression) &&
8935 expression_has_effect(cond->false_expression);
8938 case EXPR_SELECT: return false;
8939 case EXPR_ARRAY_ACCESS: return false;
8940 case EXPR_SIZEOF: return false;
8941 case EXPR_CLASSIFY_TYPE: return false;
8942 case EXPR_ALIGNOF: return false;
8944 case EXPR_FUNCNAME: return false;
8945 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8946 case EXPR_BUILTIN_CONSTANT_P: return false;
8947 case EXPR_BUILTIN_PREFETCH: return true;
8948 case EXPR_OFFSETOF: return false;
8949 case EXPR_VA_START: return true;
8950 case EXPR_VA_ARG: return true;
8951 case EXPR_STATEMENT: return true; // TODO
8952 case EXPR_COMPOUND_LITERAL: return false;
8954 case EXPR_UNARY_NEGATE: return false;
8955 case EXPR_UNARY_PLUS: return false;
8956 case EXPR_UNARY_BITWISE_NEGATE: return false;
8957 case EXPR_UNARY_NOT: return false;
8958 case EXPR_UNARY_DEREFERENCE: return false;
8959 case EXPR_UNARY_TAKE_ADDRESS: return false;
8960 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8961 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8962 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8963 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8965 /* Treat void casts as if they have an effect in order to being able to
8966 * suppress the warning */
8967 case EXPR_UNARY_CAST: {
8968 type_t *const type = skip_typeref(expr->base.type);
8969 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8972 case EXPR_UNARY_CAST_IMPLICIT: return true;
8973 case EXPR_UNARY_ASSUME: return true;
8974 case EXPR_UNARY_DELETE: return true;
8975 case EXPR_UNARY_DELETE_ARRAY: return true;
8976 case EXPR_UNARY_THROW: return true;
8978 case EXPR_BINARY_ADD: return false;
8979 case EXPR_BINARY_SUB: return false;
8980 case EXPR_BINARY_MUL: return false;
8981 case EXPR_BINARY_DIV: return false;
8982 case EXPR_BINARY_MOD: return false;
8983 case EXPR_BINARY_EQUAL: return false;
8984 case EXPR_BINARY_NOTEQUAL: return false;
8985 case EXPR_BINARY_LESS: return false;
8986 case EXPR_BINARY_LESSEQUAL: return false;
8987 case EXPR_BINARY_GREATER: return false;
8988 case EXPR_BINARY_GREATEREQUAL: return false;
8989 case EXPR_BINARY_BITWISE_AND: return false;
8990 case EXPR_BINARY_BITWISE_OR: return false;
8991 case EXPR_BINARY_BITWISE_XOR: return false;
8992 case EXPR_BINARY_SHIFTLEFT: return false;
8993 case EXPR_BINARY_SHIFTRIGHT: return false;
8994 case EXPR_BINARY_ASSIGN: return true;
8995 case EXPR_BINARY_MUL_ASSIGN: return true;
8996 case EXPR_BINARY_DIV_ASSIGN: return true;
8997 case EXPR_BINARY_MOD_ASSIGN: return true;
8998 case EXPR_BINARY_ADD_ASSIGN: return true;
8999 case EXPR_BINARY_SUB_ASSIGN: return true;
9000 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9001 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9002 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9003 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9004 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9006 /* Only examine the right hand side of && and ||, because the left hand
9007 * side already has the effect of controlling the execution of the right
9009 case EXPR_BINARY_LOGICAL_AND:
9010 case EXPR_BINARY_LOGICAL_OR:
9011 /* Only examine the right hand side of a comma expression, because the left
9012 * hand side has a separate warning */
9013 case EXPR_BINARY_COMMA:
9014 return expression_has_effect(expr->binary.right);
9016 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9017 case EXPR_BINARY_ISGREATER: return false;
9018 case EXPR_BINARY_ISGREATEREQUAL: return false;
9019 case EXPR_BINARY_ISLESS: return false;
9020 case EXPR_BINARY_ISLESSEQUAL: return false;
9021 case EXPR_BINARY_ISLESSGREATER: return false;
9022 case EXPR_BINARY_ISUNORDERED: return false;
9025 internal_errorf(HERE, "unexpected expression");
9028 static void semantic_comma(binary_expression_t *expression)
9030 if (warning.unused_value) {
9031 const expression_t *const left = expression->left;
9032 if (!expression_has_effect(left)) {
9033 warningf(&left->base.source_position,
9034 "left-hand operand of comma expression has no effect");
9037 expression->base.type = expression->right->base.type;
9041 * @param prec_r precedence of the right operand
9043 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9044 static expression_t *parse_##binexpression_type(expression_t *left) \
9046 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9047 binexpr->binary.left = left; \
9050 expression_t *right = parse_sub_expression(prec_r); \
9052 binexpr->binary.right = right; \
9053 sfunc(&binexpr->binary); \
9058 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9059 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9060 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9061 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9062 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9063 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9064 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9065 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9066 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9067 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9068 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9069 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9070 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9071 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9072 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9073 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9074 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9075 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9076 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9077 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9078 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9079 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9080 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9081 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9082 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9083 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9084 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9085 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9086 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9087 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9090 static expression_t *parse_sub_expression(precedence_t precedence)
9092 if (token.type < 0) {
9093 return expected_expression_error();
9096 expression_parser_function_t *parser
9097 = &expression_parsers[token.type];
9098 source_position_t source_position = token.source_position;
9101 if (parser->parser != NULL) {
9102 left = parser->parser();
9104 left = parse_primary_expression();
9106 assert(left != NULL);
9107 left->base.source_position = source_position;
9110 if (token.type < 0) {
9111 return expected_expression_error();
9114 parser = &expression_parsers[token.type];
9115 if (parser->infix_parser == NULL)
9117 if (parser->infix_precedence < precedence)
9120 left = parser->infix_parser(left);
9122 assert(left != NULL);
9123 assert(left->kind != EXPR_UNKNOWN);
9124 left->base.source_position = source_position;
9131 * Parse an expression.
9133 static expression_t *parse_expression(void)
9135 return parse_sub_expression(PREC_EXPRESSION);
9139 * Register a parser for a prefix-like operator.
9141 * @param parser the parser function
9142 * @param token_type the token type of the prefix token
9144 static void register_expression_parser(parse_expression_function parser,
9147 expression_parser_function_t *entry = &expression_parsers[token_type];
9149 if (entry->parser != NULL) {
9150 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9151 panic("trying to register multiple expression parsers for a token");
9153 entry->parser = parser;
9157 * Register a parser for an infix operator with given precedence.
9159 * @param parser the parser function
9160 * @param token_type the token type of the infix operator
9161 * @param precedence the precedence of the operator
9163 static void register_infix_parser(parse_expression_infix_function parser,
9164 int token_type, unsigned precedence)
9166 expression_parser_function_t *entry = &expression_parsers[token_type];
9168 if (entry->infix_parser != NULL) {
9169 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9170 panic("trying to register multiple infix expression parsers for a "
9173 entry->infix_parser = parser;
9174 entry->infix_precedence = precedence;
9178 * Initialize the expression parsers.
9180 static void init_expression_parsers(void)
9182 memset(&expression_parsers, 0, sizeof(expression_parsers));
9184 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9185 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9186 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9187 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9188 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9189 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9190 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9191 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9192 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9193 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9194 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9195 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9196 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9197 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9198 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9199 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9200 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9201 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9202 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9203 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9204 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9205 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9206 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9207 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9208 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9209 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9210 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9211 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9212 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9213 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9214 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9215 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9216 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9217 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9218 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9219 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9220 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9222 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9223 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9224 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9225 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9226 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9227 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9228 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9229 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9230 register_expression_parser(parse_sizeof, T_sizeof);
9231 register_expression_parser(parse_alignof, T___alignof__);
9232 register_expression_parser(parse_extension, T___extension__);
9233 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9234 register_expression_parser(parse_delete, T_delete);
9235 register_expression_parser(parse_throw, T_throw);
9239 * Parse a asm statement arguments specification.
9241 static asm_argument_t *parse_asm_arguments(bool is_out)
9243 asm_argument_t *result = NULL;
9244 asm_argument_t **anchor = &result;
9246 while (token.type == T_STRING_LITERAL || token.type == '[') {
9247 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9248 memset(argument, 0, sizeof(argument[0]));
9250 if (token.type == '[') {
9252 if (token.type != T_IDENTIFIER) {
9253 parse_error_expected("while parsing asm argument",
9254 T_IDENTIFIER, NULL);
9257 argument->symbol = token.v.symbol;
9262 argument->constraints = parse_string_literals();
9264 add_anchor_token(')');
9265 expression_t *expression = parse_expression();
9266 rem_anchor_token(')');
9268 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9269 * change size or type representation (e.g. int -> long is ok, but
9270 * int -> float is not) */
9271 if (expression->kind == EXPR_UNARY_CAST) {
9272 type_t *const type = expression->base.type;
9273 type_kind_t const kind = type->kind;
9274 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9277 if (kind == TYPE_ATOMIC) {
9278 atomic_type_kind_t const akind = type->atomic.akind;
9279 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9280 size = get_atomic_type_size(akind);
9282 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9283 size = get_atomic_type_size(get_intptr_kind());
9287 expression_t *const value = expression->unary.value;
9288 type_t *const value_type = value->base.type;
9289 type_kind_t const value_kind = value_type->kind;
9291 unsigned value_flags;
9292 unsigned value_size;
9293 if (value_kind == TYPE_ATOMIC) {
9294 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9295 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9296 value_size = get_atomic_type_size(value_akind);
9297 } else if (value_kind == TYPE_POINTER) {
9298 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9299 value_size = get_atomic_type_size(get_intptr_kind());
9304 if (value_flags != flags || value_size != size)
9308 } while (expression->kind == EXPR_UNARY_CAST);
9312 if (!is_lvalue(expression)) {
9313 errorf(&expression->base.source_position,
9314 "asm output argument is not an lvalue");
9317 if (argument->constraints.begin[0] == '+')
9318 mark_vars_read(expression, NULL);
9320 mark_vars_read(expression, NULL);
9322 argument->expression = expression;
9325 set_address_taken(expression, true);
9328 anchor = &argument->next;
9330 if (token.type != ',')
9341 * Parse a asm statement clobber specification.
9343 static asm_clobber_t *parse_asm_clobbers(void)
9345 asm_clobber_t *result = NULL;
9346 asm_clobber_t *last = NULL;
9348 while (token.type == T_STRING_LITERAL) {
9349 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9350 clobber->clobber = parse_string_literals();
9353 last->next = clobber;
9359 if (token.type != ',')
9368 * Parse an asm statement.
9370 static statement_t *parse_asm_statement(void)
9372 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9373 asm_statement_t *asm_statement = &statement->asms;
9377 if (token.type == T_volatile) {
9379 asm_statement->is_volatile = true;
9383 add_anchor_token(')');
9384 add_anchor_token(':');
9385 asm_statement->asm_text = parse_string_literals();
9387 if (token.type != ':') {
9388 rem_anchor_token(':');
9393 asm_statement->outputs = parse_asm_arguments(true);
9394 if (token.type != ':') {
9395 rem_anchor_token(':');
9400 asm_statement->inputs = parse_asm_arguments(false);
9401 if (token.type != ':') {
9402 rem_anchor_token(':');
9405 rem_anchor_token(':');
9408 asm_statement->clobbers = parse_asm_clobbers();
9411 rem_anchor_token(')');
9415 if (asm_statement->outputs == NULL) {
9416 /* GCC: An 'asm' instruction without any output operands will be treated
9417 * identically to a volatile 'asm' instruction. */
9418 asm_statement->is_volatile = true;
9423 return create_invalid_statement();
9427 * Parse a case statement.
9429 static statement_t *parse_case_statement(void)
9431 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9432 source_position_t *const pos = &statement->base.source_position;
9436 expression_t *const expression = parse_expression();
9437 statement->case_label.expression = expression;
9438 if (!is_constant_expression(expression)) {
9439 /* This check does not prevent the error message in all cases of an
9440 * prior error while parsing the expression. At least it catches the
9441 * common case of a mistyped enum entry. */
9442 if (is_type_valid(skip_typeref(expression->base.type))) {
9443 errorf(pos, "case label does not reduce to an integer constant");
9445 statement->case_label.is_bad = true;
9447 long const val = fold_constant(expression);
9448 statement->case_label.first_case = val;
9449 statement->case_label.last_case = val;
9453 if (token.type == T_DOTDOTDOT) {
9455 expression_t *const end_range = parse_expression();
9456 statement->case_label.end_range = end_range;
9457 if (!is_constant_expression(end_range)) {
9458 /* This check does not prevent the error message in all cases of an
9459 * prior error while parsing the expression. At least it catches the
9460 * common case of a mistyped enum entry. */
9461 if (is_type_valid(skip_typeref(end_range->base.type))) {
9462 errorf(pos, "case range does not reduce to an integer constant");
9464 statement->case_label.is_bad = true;
9466 long const val = fold_constant(end_range);
9467 statement->case_label.last_case = val;
9469 if (warning.other && val < statement->case_label.first_case) {
9470 statement->case_label.is_empty_range = true;
9471 warningf(pos, "empty range specified");
9477 PUSH_PARENT(statement);
9481 if (current_switch != NULL) {
9482 if (! statement->case_label.is_bad) {
9483 /* Check for duplicate case values */
9484 case_label_statement_t *c = &statement->case_label;
9485 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9486 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9489 if (c->last_case < l->first_case || c->first_case > l->last_case)
9492 errorf(pos, "duplicate case value (previously used %P)",
9493 &l->base.source_position);
9497 /* link all cases into the switch statement */
9498 if (current_switch->last_case == NULL) {
9499 current_switch->first_case = &statement->case_label;
9501 current_switch->last_case->next = &statement->case_label;
9503 current_switch->last_case = &statement->case_label;
9505 errorf(pos, "case label not within a switch statement");
9508 statement_t *const inner_stmt = parse_statement();
9509 statement->case_label.statement = inner_stmt;
9510 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9511 errorf(&inner_stmt->base.source_position, "declaration after case label");
9518 return create_invalid_statement();
9522 * Parse a default statement.
9524 static statement_t *parse_default_statement(void)
9526 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9530 PUSH_PARENT(statement);
9533 if (current_switch != NULL) {
9534 const case_label_statement_t *def_label = current_switch->default_label;
9535 if (def_label != NULL) {
9536 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9537 &def_label->base.source_position);
9539 current_switch->default_label = &statement->case_label;
9541 /* link all cases into the switch statement */
9542 if (current_switch->last_case == NULL) {
9543 current_switch->first_case = &statement->case_label;
9545 current_switch->last_case->next = &statement->case_label;
9547 current_switch->last_case = &statement->case_label;
9550 errorf(&statement->base.source_position,
9551 "'default' label not within a switch statement");
9554 statement_t *const inner_stmt = parse_statement();
9555 statement->case_label.statement = inner_stmt;
9556 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9557 errorf(&inner_stmt->base.source_position, "declaration after default label");
9564 return create_invalid_statement();
9568 * Parse a label statement.
9570 static statement_t *parse_label_statement(void)
9572 assert(token.type == T_IDENTIFIER);
9573 symbol_t *symbol = token.v.symbol;
9574 label_t *label = get_label(symbol);
9576 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9577 statement->label.label = label;
9581 PUSH_PARENT(statement);
9583 /* if statement is already set then the label is defined twice,
9584 * otherwise it was just mentioned in a goto/local label declaration so far
9586 if (label->statement != NULL) {
9587 errorf(HERE, "duplicate label '%Y' (declared %P)",
9588 symbol, &label->base.source_position);
9590 label->base.source_position = token.source_position;
9591 label->statement = statement;
9596 if (token.type == '}') {
9597 /* TODO only warn? */
9598 if (warning.other && false) {
9599 warningf(HERE, "label at end of compound statement");
9600 statement->label.statement = create_empty_statement();
9602 errorf(HERE, "label at end of compound statement");
9603 statement->label.statement = create_invalid_statement();
9605 } else if (token.type == ';') {
9606 /* Eat an empty statement here, to avoid the warning about an empty
9607 * statement after a label. label:; is commonly used to have a label
9608 * before a closing brace. */
9609 statement->label.statement = create_empty_statement();
9612 statement_t *const inner_stmt = parse_statement();
9613 statement->label.statement = inner_stmt;
9614 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9615 errorf(&inner_stmt->base.source_position, "declaration after label");
9619 /* remember the labels in a list for later checking */
9620 *label_anchor = &statement->label;
9621 label_anchor = &statement->label.next;
9628 * Parse an if statement.
9630 static statement_t *parse_if(void)
9632 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9636 PUSH_PARENT(statement);
9638 add_anchor_token('{');
9641 add_anchor_token(')');
9642 expression_t *const expr = parse_expression();
9643 statement->ifs.condition = expr;
9644 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9646 semantic_condition(expr, "condition of 'if'-statment");
9647 mark_vars_read(expr, NULL);
9648 rem_anchor_token(')');
9652 rem_anchor_token('{');
9654 add_anchor_token(T_else);
9655 statement->ifs.true_statement = parse_statement();
9656 rem_anchor_token(T_else);
9658 if (token.type == T_else) {
9660 statement->ifs.false_statement = parse_statement();
9668 * Check that all enums are handled in a switch.
9670 * @param statement the switch statement to check
9672 static void check_enum_cases(const switch_statement_t *statement) {
9673 const type_t *type = skip_typeref(statement->expression->base.type);
9674 if (! is_type_enum(type))
9676 const enum_type_t *enumt = &type->enumt;
9678 /* if we have a default, no warnings */
9679 if (statement->default_label != NULL)
9682 /* FIXME: calculation of value should be done while parsing */
9683 /* TODO: quadratic algorithm here. Change to an n log n one */
9684 long last_value = -1;
9685 const entity_t *entry = enumt->enume->base.next;
9686 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9687 entry = entry->base.next) {
9688 const expression_t *expression = entry->enum_value.value;
9689 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9691 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9692 if (l->expression == NULL)
9694 if (l->first_case <= value && value <= l->last_case) {
9700 warningf(&statement->base.source_position,
9701 "enumeration value '%Y' not handled in switch",
9702 entry->base.symbol);
9709 * Parse a switch statement.
9711 static statement_t *parse_switch(void)
9713 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9717 PUSH_PARENT(statement);
9720 add_anchor_token(')');
9721 expression_t *const expr = parse_expression();
9722 mark_vars_read(expr, NULL);
9723 type_t * type = skip_typeref(expr->base.type);
9724 if (is_type_integer(type)) {
9725 type = promote_integer(type);
9726 if (warning.traditional) {
9727 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9728 warningf(&expr->base.source_position,
9729 "'%T' switch expression not converted to '%T' in ISO C",
9733 } else if (is_type_valid(type)) {
9734 errorf(&expr->base.source_position,
9735 "switch quantity is not an integer, but '%T'", type);
9736 type = type_error_type;
9738 statement->switchs.expression = create_implicit_cast(expr, type);
9740 rem_anchor_token(')');
9742 switch_statement_t *rem = current_switch;
9743 current_switch = &statement->switchs;
9744 statement->switchs.body = parse_statement();
9745 current_switch = rem;
9747 if (warning.switch_default &&
9748 statement->switchs.default_label == NULL) {
9749 warningf(&statement->base.source_position, "switch has no default case");
9751 if (warning.switch_enum)
9752 check_enum_cases(&statement->switchs);
9758 return create_invalid_statement();
9761 static statement_t *parse_loop_body(statement_t *const loop)
9763 statement_t *const rem = current_loop;
9764 current_loop = loop;
9766 statement_t *const body = parse_statement();
9773 * Parse a while statement.
9775 static statement_t *parse_while(void)
9777 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9781 PUSH_PARENT(statement);
9784 add_anchor_token(')');
9785 expression_t *const cond = parse_expression();
9786 statement->whiles.condition = cond;
9787 /* §6.8.5:2 The controlling expression of an iteration statement shall
9788 * have scalar type. */
9789 semantic_condition(cond, "condition of 'while'-statement");
9790 mark_vars_read(cond, NULL);
9791 rem_anchor_token(')');
9794 statement->whiles.body = parse_loop_body(statement);
9800 return create_invalid_statement();
9804 * Parse a do statement.
9806 static statement_t *parse_do(void)
9808 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9812 PUSH_PARENT(statement);
9814 add_anchor_token(T_while);
9815 statement->do_while.body = parse_loop_body(statement);
9816 rem_anchor_token(T_while);
9820 add_anchor_token(')');
9821 expression_t *const cond = parse_expression();
9822 statement->do_while.condition = cond;
9823 /* §6.8.5:2 The controlling expression of an iteration statement shall
9824 * have scalar type. */
9825 semantic_condition(cond, "condition of 'do-while'-statement");
9826 mark_vars_read(cond, NULL);
9827 rem_anchor_token(')');
9835 return create_invalid_statement();
9839 * Parse a for statement.
9841 static statement_t *parse_for(void)
9843 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9847 PUSH_PARENT(statement);
9849 size_t const top = environment_top();
9850 scope_push(&statement->fors.scope);
9853 add_anchor_token(')');
9855 if (token.type == ';') {
9857 } else if (is_declaration_specifier(&token, false)) {
9858 parse_declaration(record_entity);
9860 add_anchor_token(';');
9861 expression_t *const init = parse_expression();
9862 statement->fors.initialisation = init;
9863 mark_vars_read(init, VAR_ANY);
9864 if (warning.unused_value && !expression_has_effect(init)) {
9865 warningf(&init->base.source_position,
9866 "initialisation of 'for'-statement has no effect");
9868 rem_anchor_token(';');
9872 if (token.type != ';') {
9873 add_anchor_token(';');
9874 expression_t *const cond = parse_expression();
9875 statement->fors.condition = cond;
9876 /* §6.8.5:2 The controlling expression of an iteration statement shall
9877 * have scalar type. */
9878 semantic_condition(cond, "condition of 'for'-statement");
9879 mark_vars_read(cond, NULL);
9880 rem_anchor_token(';');
9883 if (token.type != ')') {
9884 expression_t *const step = parse_expression();
9885 statement->fors.step = step;
9886 mark_vars_read(step, VAR_ANY);
9887 if (warning.unused_value && !expression_has_effect(step)) {
9888 warningf(&step->base.source_position,
9889 "step of 'for'-statement has no effect");
9893 rem_anchor_token(')');
9894 statement->fors.body = parse_loop_body(statement);
9896 assert(current_scope == &statement->fors.scope);
9898 environment_pop_to(top);
9905 rem_anchor_token(')');
9906 assert(current_scope == &statement->fors.scope);
9908 environment_pop_to(top);
9910 return create_invalid_statement();
9914 * Parse a goto statement.
9916 static statement_t *parse_goto(void)
9918 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9921 if (GNU_MODE && token.type == '*') {
9923 expression_t *expression = parse_expression();
9924 mark_vars_read(expression, NULL);
9926 /* Argh: although documentation says the expression must be of type void*,
9927 * gcc accepts anything that can be casted into void* without error */
9928 type_t *type = expression->base.type;
9930 if (type != type_error_type) {
9931 if (!is_type_pointer(type) && !is_type_integer(type)) {
9932 errorf(&expression->base.source_position,
9933 "cannot convert to a pointer type");
9934 } else if (warning.other && type != type_void_ptr) {
9935 warningf(&expression->base.source_position,
9936 "type of computed goto expression should be 'void*' not '%T'", type);
9938 expression = create_implicit_cast(expression, type_void_ptr);
9941 statement->gotos.expression = expression;
9943 if (token.type != T_IDENTIFIER) {
9945 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9947 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9951 symbol_t *symbol = token.v.symbol;
9954 statement->gotos.label = get_label(symbol);
9957 /* remember the goto's in a list for later checking */
9958 *goto_anchor = &statement->gotos;
9959 goto_anchor = &statement->gotos.next;
9965 return create_invalid_statement();
9969 * Parse a continue statement.
9971 static statement_t *parse_continue(void)
9973 if (current_loop == NULL) {
9974 errorf(HERE, "continue statement not within loop");
9977 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9987 * Parse a break statement.
9989 static statement_t *parse_break(void)
9991 if (current_switch == NULL && current_loop == NULL) {
9992 errorf(HERE, "break statement not within loop or switch");
9995 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10005 * Parse a __leave statement.
10007 static statement_t *parse_leave_statement(void)
10009 if (current_try == NULL) {
10010 errorf(HERE, "__leave statement not within __try");
10013 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10023 * Check if a given entity represents a local variable.
10025 static bool is_local_variable(const entity_t *entity)
10027 if (entity->kind != ENTITY_VARIABLE)
10030 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10031 case STORAGE_CLASS_AUTO:
10032 case STORAGE_CLASS_REGISTER: {
10033 const type_t *type = skip_typeref(entity->declaration.type);
10034 if (is_type_function(type)) {
10046 * Check if a given expression represents a local variable.
10048 static bool expression_is_local_variable(const expression_t *expression)
10050 if (expression->base.kind != EXPR_REFERENCE) {
10053 const entity_t *entity = expression->reference.entity;
10054 return is_local_variable(entity);
10058 * Check if a given expression represents a local variable and
10059 * return its declaration then, else return NULL.
10061 entity_t *expression_is_variable(const expression_t *expression)
10063 if (expression->base.kind != EXPR_REFERENCE) {
10066 entity_t *entity = expression->reference.entity;
10067 if (entity->kind != ENTITY_VARIABLE)
10074 * Parse a return statement.
10076 static statement_t *parse_return(void)
10080 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10082 expression_t *return_value = NULL;
10083 if (token.type != ';') {
10084 return_value = parse_expression();
10085 mark_vars_read(return_value, NULL);
10088 const type_t *const func_type = skip_typeref(current_function->base.type);
10089 assert(is_type_function(func_type));
10090 type_t *const return_type = skip_typeref(func_type->function.return_type);
10092 if (return_value != NULL) {
10093 type_t *return_value_type = skip_typeref(return_value->base.type);
10095 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10096 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10097 if (warning.other) {
10098 warningf(&statement->base.source_position,
10099 "'return' with a value, in function returning void");
10101 return_value = NULL;
10103 assign_error_t error = semantic_assign(return_type, return_value);
10104 report_assign_error(error, return_type, return_value, "'return'",
10105 &statement->base.source_position);
10106 return_value = create_implicit_cast(return_value, return_type);
10108 /* check for returning address of a local var */
10109 if (warning.other && return_value != NULL
10110 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10111 const expression_t *expression = return_value->unary.value;
10112 if (expression_is_local_variable(expression)) {
10113 warningf(&statement->base.source_position,
10114 "function returns address of local variable");
10117 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10118 warningf(&statement->base.source_position,
10119 "'return' without value, in function returning non-void");
10121 statement->returns.value = return_value;
10130 * Parse a declaration statement.
10132 static statement_t *parse_declaration_statement(void)
10134 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10136 entity_t *before = current_scope->last_entity;
10138 parse_external_declaration();
10140 parse_declaration(record_entity);
10142 if (before == NULL) {
10143 statement->declaration.declarations_begin = current_scope->entities;
10145 statement->declaration.declarations_begin = before->base.next;
10147 statement->declaration.declarations_end = current_scope->last_entity;
10153 * Parse an expression statement, ie. expr ';'.
10155 static statement_t *parse_expression_statement(void)
10157 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10159 expression_t *const expr = parse_expression();
10160 statement->expression.expression = expr;
10161 mark_vars_read(expr, VAR_ANY);
10170 * Parse a microsoft __try { } __finally { } or
10171 * __try{ } __except() { }
10173 static statement_t *parse_ms_try_statment(void)
10175 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10178 PUSH_PARENT(statement);
10180 ms_try_statement_t *rem = current_try;
10181 current_try = &statement->ms_try;
10182 statement->ms_try.try_statement = parse_compound_statement(false);
10187 if (token.type == T___except) {
10190 add_anchor_token(')');
10191 expression_t *const expr = parse_expression();
10192 mark_vars_read(expr, NULL);
10193 type_t * type = skip_typeref(expr->base.type);
10194 if (is_type_integer(type)) {
10195 type = promote_integer(type);
10196 } else if (is_type_valid(type)) {
10197 errorf(&expr->base.source_position,
10198 "__expect expression is not an integer, but '%T'", type);
10199 type = type_error_type;
10201 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10202 rem_anchor_token(')');
10204 statement->ms_try.final_statement = parse_compound_statement(false);
10205 } else if (token.type == T__finally) {
10207 statement->ms_try.final_statement = parse_compound_statement(false);
10209 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10210 return create_invalid_statement();
10214 return create_invalid_statement();
10217 static statement_t *parse_empty_statement(void)
10219 if (warning.empty_statement) {
10220 warningf(HERE, "statement is empty");
10222 statement_t *const statement = create_empty_statement();
10227 static statement_t *parse_local_label_declaration(void)
10229 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10233 entity_t *begin = NULL, *end = NULL;
10236 if (token.type != T_IDENTIFIER) {
10237 parse_error_expected("while parsing local label declaration",
10238 T_IDENTIFIER, NULL);
10241 symbol_t *symbol = token.v.symbol;
10242 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10243 if (entity != NULL && entity->base.parent_scope == current_scope) {
10244 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10245 symbol, &entity->base.source_position);
10247 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10249 entity->base.parent_scope = current_scope;
10250 entity->base.namespc = NAMESPACE_LABEL;
10251 entity->base.source_position = token.source_position;
10252 entity->base.symbol = symbol;
10255 end->base.next = entity;
10260 environment_push(entity);
10264 if (token.type != ',')
10270 statement->declaration.declarations_begin = begin;
10271 statement->declaration.declarations_end = end;
10275 static void parse_namespace_definition(void)
10279 entity_t *entity = NULL;
10280 symbol_t *symbol = NULL;
10282 if (token.type == T_IDENTIFIER) {
10283 symbol = token.v.symbol;
10286 entity = get_entity(symbol, NAMESPACE_NORMAL);
10287 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10288 && entity->base.parent_scope == current_scope) {
10289 error_redefined_as_different_kind(&token.source_position,
10290 entity, ENTITY_NAMESPACE);
10295 if (entity == NULL) {
10296 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10297 entity->base.symbol = symbol;
10298 entity->base.source_position = token.source_position;
10299 entity->base.namespc = NAMESPACE_NORMAL;
10300 entity->base.parent_scope = current_scope;
10303 if (token.type == '=') {
10304 /* TODO: parse namespace alias */
10305 panic("namespace alias definition not supported yet");
10308 environment_push(entity);
10309 append_entity(current_scope, entity);
10311 size_t const top = environment_top();
10312 scope_push(&entity->namespacee.members);
10319 assert(current_scope == &entity->namespacee.members);
10321 environment_pop_to(top);
10325 * Parse a statement.
10326 * There's also parse_statement() which additionally checks for
10327 * "statement has no effect" warnings
10329 static statement_t *intern_parse_statement(void)
10331 statement_t *statement = NULL;
10333 /* declaration or statement */
10334 add_anchor_token(';');
10335 switch (token.type) {
10336 case T_IDENTIFIER: {
10337 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10338 if (la1_type == ':') {
10339 statement = parse_label_statement();
10340 } else if (is_typedef_symbol(token.v.symbol)) {
10341 statement = parse_declaration_statement();
10343 /* it's an identifier, the grammar says this must be an
10344 * expression statement. However it is common that users mistype
10345 * declaration types, so we guess a bit here to improve robustness
10346 * for incorrect programs */
10347 switch (la1_type) {
10350 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10351 goto expression_statment;
10356 statement = parse_declaration_statement();
10360 expression_statment:
10361 statement = parse_expression_statement();
10368 case T___extension__:
10369 /* This can be a prefix to a declaration or an expression statement.
10370 * We simply eat it now and parse the rest with tail recursion. */
10373 } while (token.type == T___extension__);
10374 bool old_gcc_extension = in_gcc_extension;
10375 in_gcc_extension = true;
10376 statement = parse_statement();
10377 in_gcc_extension = old_gcc_extension;
10381 statement = parse_declaration_statement();
10385 statement = parse_local_label_declaration();
10388 case ';': statement = parse_empty_statement(); break;
10389 case '{': statement = parse_compound_statement(false); break;
10390 case T___leave: statement = parse_leave_statement(); break;
10391 case T___try: statement = parse_ms_try_statment(); break;
10392 case T_asm: statement = parse_asm_statement(); break;
10393 case T_break: statement = parse_break(); break;
10394 case T_case: statement = parse_case_statement(); break;
10395 case T_continue: statement = parse_continue(); break;
10396 case T_default: statement = parse_default_statement(); break;
10397 case T_do: statement = parse_do(); break;
10398 case T_for: statement = parse_for(); break;
10399 case T_goto: statement = parse_goto(); break;
10400 case T_if: statement = parse_if(); break;
10401 case T_return: statement = parse_return(); break;
10402 case T_switch: statement = parse_switch(); break;
10403 case T_while: statement = parse_while(); break;
10406 statement = parse_expression_statement();
10410 errorf(HERE, "unexpected token %K while parsing statement", &token);
10411 statement = create_invalid_statement();
10416 rem_anchor_token(';');
10418 assert(statement != NULL
10419 && statement->base.source_position.input_name != NULL);
10425 * parse a statement and emits "statement has no effect" warning if needed
10426 * (This is really a wrapper around intern_parse_statement with check for 1
10427 * single warning. It is needed, because for statement expressions we have
10428 * to avoid the warning on the last statement)
10430 static statement_t *parse_statement(void)
10432 statement_t *statement = intern_parse_statement();
10434 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10435 expression_t *expression = statement->expression.expression;
10436 if (!expression_has_effect(expression)) {
10437 warningf(&expression->base.source_position,
10438 "statement has no effect");
10446 * Parse a compound statement.
10448 static statement_t *parse_compound_statement(bool inside_expression_statement)
10450 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10452 PUSH_PARENT(statement);
10455 add_anchor_token('}');
10457 size_t const top = environment_top();
10458 scope_push(&statement->compound.scope);
10460 statement_t **anchor = &statement->compound.statements;
10461 bool only_decls_so_far = true;
10462 while (token.type != '}') {
10463 if (token.type == T_EOF) {
10464 errorf(&statement->base.source_position,
10465 "EOF while parsing compound statement");
10468 statement_t *sub_statement = intern_parse_statement();
10469 if (is_invalid_statement(sub_statement)) {
10470 /* an error occurred. if we are at an anchor, return */
10476 if (warning.declaration_after_statement) {
10477 if (sub_statement->kind != STATEMENT_DECLARATION) {
10478 only_decls_so_far = false;
10479 } else if (!only_decls_so_far) {
10480 warningf(&sub_statement->base.source_position,
10481 "ISO C90 forbids mixed declarations and code");
10485 *anchor = sub_statement;
10487 while (sub_statement->base.next != NULL)
10488 sub_statement = sub_statement->base.next;
10490 anchor = &sub_statement->base.next;
10494 /* look over all statements again to produce no effect warnings */
10495 if (warning.unused_value) {
10496 statement_t *sub_statement = statement->compound.statements;
10497 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10498 if (sub_statement->kind != STATEMENT_EXPRESSION)
10500 /* don't emit a warning for the last expression in an expression
10501 * statement as it has always an effect */
10502 if (inside_expression_statement && sub_statement->base.next == NULL)
10505 expression_t *expression = sub_statement->expression.expression;
10506 if (!expression_has_effect(expression)) {
10507 warningf(&expression->base.source_position,
10508 "statement has no effect");
10514 rem_anchor_token('}');
10515 assert(current_scope == &statement->compound.scope);
10517 environment_pop_to(top);
10524 * Check for unused global static functions and variables
10526 static void check_unused_globals(void)
10528 if (!warning.unused_function && !warning.unused_variable)
10531 for (const entity_t *entity = file_scope->entities; entity != NULL;
10532 entity = entity->base.next) {
10533 if (!is_declaration(entity))
10536 const declaration_t *declaration = &entity->declaration;
10537 if (declaration->used ||
10538 declaration->modifiers & DM_UNUSED ||
10539 declaration->modifiers & DM_USED ||
10540 declaration->storage_class != STORAGE_CLASS_STATIC)
10543 type_t *const type = declaration->type;
10545 if (entity->kind == ENTITY_FUNCTION) {
10546 /* inhibit warning for static inline functions */
10547 if (entity->function.is_inline)
10550 s = entity->function.statement != NULL ? "defined" : "declared";
10555 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10556 type, declaration->base.symbol, s);
10560 static void parse_global_asm(void)
10562 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10567 statement->asms.asm_text = parse_string_literals();
10568 statement->base.next = unit->global_asm;
10569 unit->global_asm = statement;
10577 static void parse_linkage_specification(void)
10580 assert(token.type == T_STRING_LITERAL);
10582 const char *linkage = parse_string_literals().begin;
10584 linkage_kind_t old_linkage = current_linkage;
10585 linkage_kind_t new_linkage;
10586 if (strcmp(linkage, "C") == 0) {
10587 new_linkage = LINKAGE_C;
10588 } else if (strcmp(linkage, "C++") == 0) {
10589 new_linkage = LINKAGE_CXX;
10591 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10592 new_linkage = LINKAGE_INVALID;
10594 current_linkage = new_linkage;
10596 if (token.type == '{') {
10605 assert(current_linkage == new_linkage);
10606 current_linkage = old_linkage;
10609 static void parse_external(void)
10611 switch (token.type) {
10612 DECLARATION_START_NO_EXTERN
10614 case T___extension__:
10615 case '(': /* for function declarations with implicit return type and
10616 * parenthesized declarator, i.e. (f)(void); */
10617 parse_external_declaration();
10621 if (look_ahead(1)->type == T_STRING_LITERAL) {
10622 parse_linkage_specification();
10624 parse_external_declaration();
10629 parse_global_asm();
10633 parse_namespace_definition();
10637 if (!strict_mode) {
10639 warningf(HERE, "stray ';' outside of function");
10646 errorf(HERE, "stray %K outside of function", &token);
10647 if (token.type == '(' || token.type == '{' || token.type == '[')
10648 eat_until_matching_token(token.type);
10654 static void parse_externals(void)
10656 add_anchor_token('}');
10657 add_anchor_token(T_EOF);
10660 unsigned char token_anchor_copy[T_LAST_TOKEN];
10661 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10664 while (token.type != T_EOF && token.type != '}') {
10666 bool anchor_leak = false;
10667 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10668 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10670 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10671 anchor_leak = true;
10674 if (in_gcc_extension) {
10675 errorf(HERE, "Leaked __extension__");
10676 anchor_leak = true;
10686 rem_anchor_token(T_EOF);
10687 rem_anchor_token('}');
10691 * Parse a translation unit.
10693 static void parse_translation_unit(void)
10695 add_anchor_token(T_EOF);
10700 if (token.type == T_EOF)
10703 errorf(HERE, "stray %K outside of function", &token);
10704 if (token.type == '(' || token.type == '{' || token.type == '[')
10705 eat_until_matching_token(token.type);
10713 * @return the translation unit or NULL if errors occurred.
10715 void start_parsing(void)
10717 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10718 label_stack = NEW_ARR_F(stack_entry_t, 0);
10719 diagnostic_count = 0;
10723 type_set_output(stderr);
10724 ast_set_output(stderr);
10726 assert(unit == NULL);
10727 unit = allocate_ast_zero(sizeof(unit[0]));
10729 assert(file_scope == NULL);
10730 file_scope = &unit->scope;
10732 assert(current_scope == NULL);
10733 scope_push(&unit->scope);
10736 translation_unit_t *finish_parsing(void)
10738 /* do NOT use scope_pop() here, this will crash, will it by hand */
10739 assert(current_scope == &unit->scope);
10740 current_scope = NULL;
10742 assert(file_scope == &unit->scope);
10743 check_unused_globals();
10746 DEL_ARR_F(environment_stack);
10747 DEL_ARR_F(label_stack);
10749 translation_unit_t *result = unit;
10756 lookahead_bufpos = 0;
10757 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10760 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10761 parse_translation_unit();
10765 * Initialize the parser.
10767 void init_parser(void)
10769 sym_anonymous = symbol_table_insert("<anonymous>");
10771 if (c_mode & _MS) {
10772 /* add predefined symbols for extended-decl-modifier */
10773 sym_align = symbol_table_insert("align");
10774 sym_allocate = symbol_table_insert("allocate");
10775 sym_dllimport = symbol_table_insert("dllimport");
10776 sym_dllexport = symbol_table_insert("dllexport");
10777 sym_naked = symbol_table_insert("naked");
10778 sym_noinline = symbol_table_insert("noinline");
10779 sym_noreturn = symbol_table_insert("noreturn");
10780 sym_nothrow = symbol_table_insert("nothrow");
10781 sym_novtable = symbol_table_insert("novtable");
10782 sym_property = symbol_table_insert("property");
10783 sym_get = symbol_table_insert("get");
10784 sym_put = symbol_table_insert("put");
10785 sym_selectany = symbol_table_insert("selectany");
10786 sym_thread = symbol_table_insert("thread");
10787 sym_uuid = symbol_table_insert("uuid");
10788 sym_deprecated = symbol_table_insert("deprecated");
10789 sym_restrict = symbol_table_insert("restrict");
10790 sym_noalias = symbol_table_insert("noalias");
10792 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10794 init_expression_parsers();
10795 obstack_init(&temp_obst);
10797 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10798 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10802 * Terminate the parser.
10804 void exit_parser(void)
10806 obstack_free(&temp_obst, NULL);