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);
192 typedef enum declarator_flags_t {
194 DECL_MAY_BE_ABSTRACT = 1U << 0,
195 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
196 DECL_IS_PARAMETER = 1U << 2
197 } declarator_flags_t;
199 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
200 declarator_flags_t flags);
202 static entity_t *record_entity(entity_t *entity, bool is_definition);
204 static void semantic_comparison(binary_expression_t *expression);
206 #define STORAGE_CLASSES \
207 STORAGE_CLASSES_NO_EXTERN \
210 #define STORAGE_CLASSES_NO_EXTERN \
217 #define TYPE_QUALIFIERS \
222 case T__forceinline: \
223 case T___attribute__:
225 #define COMPLEX_SPECIFIERS \
227 #define IMAGINARY_SPECIFIERS \
230 #define TYPE_SPECIFIERS \
232 case T___builtin_va_list: \
251 #define DECLARATION_START \
256 #define DECLARATION_START_NO_EXTERN \
257 STORAGE_CLASSES_NO_EXTERN \
261 #define TYPENAME_START \
265 #define EXPRESSION_START \
274 case T_CHARACTER_CONSTANT: \
275 case T_FLOATINGPOINT: \
279 case T_STRING_LITERAL: \
280 case T_WIDE_CHARACTER_CONSTANT: \
281 case T_WIDE_STRING_LITERAL: \
282 case T___FUNCDNAME__: \
283 case T___FUNCSIG__: \
284 case T___FUNCTION__: \
285 case T___PRETTY_FUNCTION__: \
286 case T___alignof__: \
287 case T___builtin_alloca: \
288 case T___builtin_classify_type: \
289 case T___builtin_constant_p: \
290 case T___builtin_expect: \
291 case T___builtin_huge_val: \
292 case T___builtin_inf: \
293 case T___builtin_inff: \
294 case T___builtin_infl: \
295 case T___builtin_isgreater: \
296 case T___builtin_isgreaterequal: \
297 case T___builtin_isless: \
298 case T___builtin_islessequal: \
299 case T___builtin_islessgreater: \
300 case T___builtin_isunordered: \
301 case T___builtin_nan: \
302 case T___builtin_nanf: \
303 case T___builtin_nanl: \
304 case T___builtin_offsetof: \
305 case T___builtin_prefetch: \
306 case T___builtin_va_arg: \
307 case T___builtin_va_end: \
308 case T___builtin_va_start: \
319 * Allocate an AST node with given size and
320 * initialize all fields with zero.
322 static void *allocate_ast_zero(size_t size)
324 void *res = allocate_ast(size);
325 memset(res, 0, size);
329 static size_t get_entity_struct_size(entity_kind_t kind)
331 static const size_t sizes[] = {
332 [ENTITY_VARIABLE] = sizeof(variable_t),
333 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
334 [ENTITY_FUNCTION] = sizeof(function_t),
335 [ENTITY_TYPEDEF] = sizeof(typedef_t),
336 [ENTITY_STRUCT] = sizeof(compound_t),
337 [ENTITY_UNION] = sizeof(compound_t),
338 [ENTITY_ENUM] = sizeof(enum_t),
339 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
340 [ENTITY_LABEL] = sizeof(label_t),
341 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
342 [ENTITY_NAMESPACE] = sizeof(namespace_t)
344 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
345 assert(sizes[kind] != 0);
349 static entity_t *allocate_entity_zero(entity_kind_t kind)
351 size_t size = get_entity_struct_size(kind);
352 entity_t *entity = allocate_ast_zero(size);
358 * Returns the size of a statement node.
360 * @param kind the statement kind
362 static size_t get_statement_struct_size(statement_kind_t kind)
364 static const size_t sizes[] = {
365 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
366 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
367 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
368 [STATEMENT_RETURN] = sizeof(return_statement_t),
369 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
370 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
371 [STATEMENT_IF] = sizeof(if_statement_t),
372 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
373 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
374 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
375 [STATEMENT_BREAK] = sizeof(statement_base_t),
376 [STATEMENT_GOTO] = sizeof(goto_statement_t),
377 [STATEMENT_LABEL] = sizeof(label_statement_t),
378 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
379 [STATEMENT_WHILE] = sizeof(while_statement_t),
380 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
381 [STATEMENT_FOR] = sizeof(for_statement_t),
382 [STATEMENT_ASM] = sizeof(asm_statement_t),
383 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
384 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
386 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
387 assert(sizes[kind] != 0);
392 * Returns the size of an expression node.
394 * @param kind the expression kind
396 static size_t get_expression_struct_size(expression_kind_t kind)
398 static const size_t sizes[] = {
399 [EXPR_INVALID] = sizeof(expression_base_t),
400 [EXPR_REFERENCE] = sizeof(reference_expression_t),
401 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
402 [EXPR_CONST] = sizeof(const_expression_t),
403 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
404 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
405 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
406 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
407 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
408 [EXPR_CALL] = sizeof(call_expression_t),
409 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
410 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
411 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
412 [EXPR_SELECT] = sizeof(select_expression_t),
413 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
414 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
415 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
416 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
417 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
418 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
419 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
420 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
421 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
422 [EXPR_VA_START] = sizeof(va_start_expression_t),
423 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
424 [EXPR_STATEMENT] = sizeof(statement_expression_t),
425 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
427 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
428 return sizes[EXPR_UNARY_FIRST];
430 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
431 return sizes[EXPR_BINARY_FIRST];
433 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
434 assert(sizes[kind] != 0);
439 * Allocate a statement node of given kind and initialize all
442 static statement_t *allocate_statement_zero(statement_kind_t kind)
444 size_t size = get_statement_struct_size(kind);
445 statement_t *res = allocate_ast_zero(size);
447 res->base.kind = kind;
448 res->base.parent = current_parent;
449 res->base.source_position = token.source_position;
454 * Allocate an expression node of given kind and initialize all
457 static expression_t *allocate_expression_zero(expression_kind_t kind)
459 size_t size = get_expression_struct_size(kind);
460 expression_t *res = allocate_ast_zero(size);
462 res->base.kind = kind;
463 res->base.type = type_error_type;
464 res->base.source_position = token.source_position;
469 * Creates a new invalid expression.
471 static expression_t *create_invalid_expression(void)
473 return allocate_expression_zero(EXPR_INVALID);
477 * Creates a new invalid statement.
479 static statement_t *create_invalid_statement(void)
481 return allocate_statement_zero(STATEMENT_INVALID);
485 * Allocate a new empty statement.
487 static statement_t *create_empty_statement(void)
489 return allocate_statement_zero(STATEMENT_EMPTY);
493 * Returns the size of a type node.
495 * @param kind the type kind
497 static size_t get_type_struct_size(type_kind_t kind)
499 static const size_t sizes[] = {
500 [TYPE_ATOMIC] = sizeof(atomic_type_t),
501 [TYPE_COMPLEX] = sizeof(complex_type_t),
502 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
503 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
504 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
505 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
506 [TYPE_ENUM] = sizeof(enum_type_t),
507 [TYPE_FUNCTION] = sizeof(function_type_t),
508 [TYPE_POINTER] = sizeof(pointer_type_t),
509 [TYPE_ARRAY] = sizeof(array_type_t),
510 [TYPE_BUILTIN] = sizeof(builtin_type_t),
511 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
512 [TYPE_TYPEOF] = sizeof(typeof_type_t),
514 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
515 assert(kind <= TYPE_TYPEOF);
516 assert(sizes[kind] != 0);
521 * Allocate a type node of given kind and initialize all
524 * @param kind type kind to allocate
526 static type_t *allocate_type_zero(type_kind_t kind)
528 size_t size = get_type_struct_size(kind);
529 type_t *res = obstack_alloc(type_obst, size);
530 memset(res, 0, size);
531 res->base.kind = kind;
537 * Returns the size of an initializer node.
539 * @param kind the initializer kind
541 static size_t get_initializer_size(initializer_kind_t kind)
543 static const size_t sizes[] = {
544 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
545 [INITIALIZER_STRING] = sizeof(initializer_string_t),
546 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
547 [INITIALIZER_LIST] = sizeof(initializer_list_t),
548 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
550 assert(kind < sizeof(sizes) / sizeof(*sizes));
551 assert(sizes[kind] != 0);
556 * Allocate an initializer node of given kind and initialize all
559 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
561 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
568 * Free a type from the type obstack.
570 static void free_type(void *type)
572 obstack_free(type_obst, type);
576 * Returns the index of the top element of the environment stack.
578 static size_t environment_top(void)
580 return ARR_LEN(environment_stack);
584 * Returns the index of the top element of the global label stack.
586 static size_t label_top(void)
588 return ARR_LEN(label_stack);
592 * Return the next token.
594 static inline void next_token(void)
596 token = lookahead_buffer[lookahead_bufpos];
597 lookahead_buffer[lookahead_bufpos] = lexer_token;
600 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
603 print_token(stderr, &token);
604 fprintf(stderr, "\n");
609 * Return the next token with a given lookahead.
611 static inline const token_t *look_ahead(int num)
613 assert(num > 0 && num <= MAX_LOOKAHEAD);
614 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
615 return &lookahead_buffer[pos];
619 * Adds a token to the token anchor set (a multi-set).
621 static void add_anchor_token(int token_type)
623 assert(0 <= token_type && token_type < T_LAST_TOKEN);
624 ++token_anchor_set[token_type];
627 static int save_and_reset_anchor_state(int token_type)
629 assert(0 <= token_type && token_type < T_LAST_TOKEN);
630 int count = token_anchor_set[token_type];
631 token_anchor_set[token_type] = 0;
635 static void restore_anchor_state(int token_type, int count)
637 assert(0 <= token_type && token_type < T_LAST_TOKEN);
638 token_anchor_set[token_type] = count;
642 * Remove a token from the token anchor set (a multi-set).
644 static void rem_anchor_token(int token_type)
646 assert(0 <= token_type && token_type < T_LAST_TOKEN);
647 assert(token_anchor_set[token_type] != 0);
648 --token_anchor_set[token_type];
651 static bool at_anchor(void)
655 return token_anchor_set[token.type];
659 * Eat tokens until a matching token is found.
661 static void eat_until_matching_token(int type)
665 case '(': end_token = ')'; break;
666 case '{': end_token = '}'; break;
667 case '[': end_token = ']'; break;
668 default: end_token = type; break;
671 unsigned parenthesis_count = 0;
672 unsigned brace_count = 0;
673 unsigned bracket_count = 0;
674 while (token.type != end_token ||
675 parenthesis_count != 0 ||
677 bracket_count != 0) {
678 switch (token.type) {
680 case '(': ++parenthesis_count; break;
681 case '{': ++brace_count; break;
682 case '[': ++bracket_count; break;
685 if (parenthesis_count > 0)
695 if (bracket_count > 0)
698 if (token.type == end_token &&
699 parenthesis_count == 0 &&
713 * Eat input tokens until an anchor is found.
715 static void eat_until_anchor(void)
717 while (token_anchor_set[token.type] == 0) {
718 if (token.type == '(' || token.type == '{' || token.type == '[')
719 eat_until_matching_token(token.type);
724 static void eat_block(void)
726 eat_until_matching_token('{');
727 if (token.type == '}')
731 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
734 * Report a parse error because an expected token was not found.
737 #if defined __GNUC__ && __GNUC__ >= 4
738 __attribute__((sentinel))
740 void parse_error_expected(const char *message, ...)
742 if (message != NULL) {
743 errorf(HERE, "%s", message);
746 va_start(ap, message);
747 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
752 * Report an incompatible type.
754 static void type_error_incompatible(const char *msg,
755 const source_position_t *source_position, type_t *type1, type_t *type2)
757 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
762 * Expect the the current token is the expected token.
763 * If not, generate an error, eat the current statement,
764 * and goto the end_error label.
766 #define expect(expected) \
768 if (UNLIKELY(token.type != (expected))) { \
769 parse_error_expected(NULL, (expected), NULL); \
770 add_anchor_token(expected); \
771 eat_until_anchor(); \
772 if (token.type == expected) \
774 rem_anchor_token(expected); \
780 static void scope_push(scope_t *new_scope)
782 if (current_scope != NULL) {
783 new_scope->depth = current_scope->depth + 1;
785 new_scope->parent = current_scope;
786 current_scope = new_scope;
789 static void scope_pop(void)
791 current_scope = current_scope->parent;
795 * Search an entity by its symbol in a given namespace.
797 static entity_t *get_entity(const symbol_t *const symbol,
798 namespace_tag_t namespc)
800 entity_t *entity = symbol->entity;
801 for (; entity != NULL; entity = entity->base.symbol_next) {
802 if (entity->base.namespc == namespc)
810 * pushs an entity on the environment stack and links the corresponding symbol
813 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
815 symbol_t *symbol = entity->base.symbol;
816 entity_namespace_t namespc = entity->base.namespc;
817 assert(namespc != NAMESPACE_INVALID);
819 /* replace/add entity into entity list of the symbol */
822 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
827 /* replace an entry? */
828 if (iter->base.namespc == namespc) {
829 entity->base.symbol_next = iter->base.symbol_next;
835 /* remember old declaration */
837 entry.symbol = symbol;
838 entry.old_entity = iter;
839 entry.namespc = namespc;
840 ARR_APP1(stack_entry_t, *stack_ptr, entry);
844 * Push an entity on the environment stack.
846 static void environment_push(entity_t *entity)
848 assert(entity->base.source_position.input_name != NULL);
849 assert(entity->base.parent_scope != NULL);
850 stack_push(&environment_stack, entity);
854 * Push a declaration on the global label stack.
856 * @param declaration the declaration
858 static void label_push(entity_t *label)
860 /* we abuse the parameters scope as parent for the labels */
861 label->base.parent_scope = ¤t_function->parameters;
862 stack_push(&label_stack, label);
866 * pops symbols from the environment stack until @p new_top is the top element
868 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
870 stack_entry_t *stack = *stack_ptr;
871 size_t top = ARR_LEN(stack);
874 assert(new_top <= top);
878 for (i = top; i > new_top; --i) {
879 stack_entry_t *entry = &stack[i - 1];
881 entity_t *old_entity = entry->old_entity;
882 symbol_t *symbol = entry->symbol;
883 entity_namespace_t namespc = entry->namespc;
885 /* replace with old_entity/remove */
888 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
890 assert(iter != NULL);
891 /* replace an entry? */
892 if (iter->base.namespc == namespc)
896 /* restore definition from outer scopes (if there was one) */
897 if (old_entity != NULL) {
898 old_entity->base.symbol_next = iter->base.symbol_next;
899 *anchor = old_entity;
901 /* remove entry from list */
902 *anchor = iter->base.symbol_next;
906 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
910 * Pop all entries from the environment stack until the new_top
913 * @param new_top the new stack top
915 static void environment_pop_to(size_t new_top)
917 stack_pop_to(&environment_stack, new_top);
921 * Pop all entries from the global label stack until the new_top
924 * @param new_top the new stack top
926 static void label_pop_to(size_t new_top)
928 stack_pop_to(&label_stack, new_top);
931 static int get_akind_rank(atomic_type_kind_t akind)
936 static int get_rank(const type_t *type)
938 assert(!is_typeref(type));
939 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
940 * and esp. footnote 108). However we can't fold constants (yet), so we
941 * can't decide whether unsigned int is possible, while int always works.
942 * (unsigned int would be preferable when possible... for stuff like
943 * struct { enum { ... } bla : 4; } ) */
944 if (type->kind == TYPE_ENUM)
945 return get_akind_rank(ATOMIC_TYPE_INT);
947 assert(type->kind == TYPE_ATOMIC);
948 return get_akind_rank(type->atomic.akind);
951 static type_t *promote_integer(type_t *type)
953 if (type->kind == TYPE_BITFIELD)
954 type = type->bitfield.base_type;
956 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
963 * Create a cast expression.
965 * @param expression the expression to cast
966 * @param dest_type the destination type
968 static expression_t *create_cast_expression(expression_t *expression,
971 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
973 cast->unary.value = expression;
974 cast->base.type = dest_type;
980 * Check if a given expression represents the 0 pointer constant.
982 static bool is_null_pointer_constant(const expression_t *expression)
984 /* skip void* cast */
985 if (expression->kind == EXPR_UNARY_CAST
986 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
987 expression = expression->unary.value;
990 /* TODO: not correct yet, should be any constant integer expression
991 * which evaluates to 0 */
992 if (expression->kind != EXPR_CONST)
995 type_t *const type = skip_typeref(expression->base.type);
996 if (!is_type_integer(type))
999 return expression->conste.v.int_value == 0;
1003 * Create an implicit cast expression.
1005 * @param expression the expression to cast
1006 * @param dest_type the destination type
1008 static expression_t *create_implicit_cast(expression_t *expression,
1011 type_t *const source_type = expression->base.type;
1013 if (source_type == dest_type)
1016 return create_cast_expression(expression, dest_type);
1019 typedef enum assign_error_t {
1021 ASSIGN_ERROR_INCOMPATIBLE,
1022 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1023 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1024 ASSIGN_WARNING_POINTER_FROM_INT,
1025 ASSIGN_WARNING_INT_FROM_POINTER
1028 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1029 const expression_t *const right,
1030 const char *context,
1031 const source_position_t *source_position)
1033 type_t *const orig_type_right = right->base.type;
1034 type_t *const type_left = skip_typeref(orig_type_left);
1035 type_t *const type_right = skip_typeref(orig_type_right);
1038 case ASSIGN_SUCCESS:
1040 case ASSIGN_ERROR_INCOMPATIBLE:
1041 errorf(source_position,
1042 "destination type '%T' in %s is incompatible with type '%T'",
1043 orig_type_left, context, orig_type_right);
1046 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1047 if (warning.other) {
1048 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1049 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1051 /* the left type has all qualifiers from the right type */
1052 unsigned missing_qualifiers
1053 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1054 warningf(source_position,
1055 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1056 orig_type_left, context, orig_type_right, missing_qualifiers);
1061 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1062 if (warning.other) {
1063 warningf(source_position,
1064 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1065 orig_type_left, context, right, orig_type_right);
1069 case ASSIGN_WARNING_POINTER_FROM_INT:
1070 if (warning.other) {
1071 warningf(source_position,
1072 "%s makes pointer '%T' from integer '%T' without a cast",
1073 context, orig_type_left, orig_type_right);
1077 case ASSIGN_WARNING_INT_FROM_POINTER:
1078 if (warning.other) {
1079 warningf(source_position,
1080 "%s makes integer '%T' from pointer '%T' without a cast",
1081 context, orig_type_left, orig_type_right);
1086 panic("invalid error value");
1090 /** Implements the rules from § 6.5.16.1 */
1091 static assign_error_t semantic_assign(type_t *orig_type_left,
1092 const expression_t *const right)
1094 type_t *const orig_type_right = right->base.type;
1095 type_t *const type_left = skip_typeref(orig_type_left);
1096 type_t *const type_right = skip_typeref(orig_type_right);
1098 if (is_type_pointer(type_left)) {
1099 if (is_null_pointer_constant(right)) {
1100 return ASSIGN_SUCCESS;
1101 } else if (is_type_pointer(type_right)) {
1102 type_t *points_to_left
1103 = skip_typeref(type_left->pointer.points_to);
1104 type_t *points_to_right
1105 = skip_typeref(type_right->pointer.points_to);
1106 assign_error_t res = ASSIGN_SUCCESS;
1108 /* the left type has all qualifiers from the right type */
1109 unsigned missing_qualifiers
1110 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1111 if (missing_qualifiers != 0) {
1112 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1115 points_to_left = get_unqualified_type(points_to_left);
1116 points_to_right = get_unqualified_type(points_to_right);
1118 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1121 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1122 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1123 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1126 if (!types_compatible(points_to_left, points_to_right)) {
1127 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1131 } else if (is_type_integer(type_right)) {
1132 return ASSIGN_WARNING_POINTER_FROM_INT;
1134 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1135 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1136 && is_type_pointer(type_right))) {
1137 return ASSIGN_SUCCESS;
1138 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1139 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1140 type_t *const unqual_type_left = get_unqualified_type(type_left);
1141 type_t *const unqual_type_right = get_unqualified_type(type_right);
1142 if (types_compatible(unqual_type_left, unqual_type_right)) {
1143 return ASSIGN_SUCCESS;
1145 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1146 return ASSIGN_WARNING_INT_FROM_POINTER;
1149 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1150 return ASSIGN_SUCCESS;
1152 return ASSIGN_ERROR_INCOMPATIBLE;
1155 static expression_t *parse_constant_expression(void)
1157 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1159 if (!is_constant_expression(result)) {
1160 errorf(&result->base.source_position,
1161 "expression '%E' is not constant\n", result);
1167 static expression_t *parse_assignment_expression(void)
1169 return parse_sub_expression(PREC_ASSIGNMENT);
1172 static string_t parse_string_literals(void)
1174 assert(token.type == T_STRING_LITERAL);
1175 string_t result = token.v.string;
1179 while (token.type == T_STRING_LITERAL) {
1180 result = concat_strings(&result, &token.v.string);
1187 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1188 [GNU_AK_CONST] = "const",
1189 [GNU_AK_VOLATILE] = "volatile",
1190 [GNU_AK_CDECL] = "cdecl",
1191 [GNU_AK_STDCALL] = "stdcall",
1192 [GNU_AK_FASTCALL] = "fastcall",
1193 [GNU_AK_DEPRECATED] = "deprecated",
1194 [GNU_AK_NOINLINE] = "noinline",
1195 [GNU_AK_NORETURN] = "noreturn",
1196 [GNU_AK_NAKED] = "naked",
1197 [GNU_AK_PURE] = "pure",
1198 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1199 [GNU_AK_MALLOC] = "malloc",
1200 [GNU_AK_WEAK] = "weak",
1201 [GNU_AK_CONSTRUCTOR] = "constructor",
1202 [GNU_AK_DESTRUCTOR] = "destructor",
1203 [GNU_AK_NOTHROW] = "nothrow",
1204 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1205 [GNU_AK_COMMON] = "common",
1206 [GNU_AK_NOCOMMON] = "nocommon",
1207 [GNU_AK_PACKED] = "packed",
1208 [GNU_AK_SHARED] = "shared",
1209 [GNU_AK_NOTSHARED] = "notshared",
1210 [GNU_AK_USED] = "used",
1211 [GNU_AK_UNUSED] = "unused",
1212 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1213 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1214 [GNU_AK_LONGCALL] = "longcall",
1215 [GNU_AK_SHORTCALL] = "shortcall",
1216 [GNU_AK_LONG_CALL] = "long_call",
1217 [GNU_AK_SHORT_CALL] = "short_call",
1218 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1219 [GNU_AK_INTERRUPT] = "interrupt",
1220 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1221 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1222 [GNU_AK_NESTING] = "nesting",
1223 [GNU_AK_NEAR] = "near",
1224 [GNU_AK_FAR] = "far",
1225 [GNU_AK_SIGNAL] = "signal",
1226 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1227 [GNU_AK_TINY_DATA] = "tiny_data",
1228 [GNU_AK_SAVEALL] = "saveall",
1229 [GNU_AK_FLATTEN] = "flatten",
1230 [GNU_AK_SSEREGPARM] = "sseregparm",
1231 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1232 [GNU_AK_RETURN_TWICE] = "return_twice",
1233 [GNU_AK_MAY_ALIAS] = "may_alias",
1234 [GNU_AK_MS_STRUCT] = "ms_struct",
1235 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1236 [GNU_AK_DLLIMPORT] = "dllimport",
1237 [GNU_AK_DLLEXPORT] = "dllexport",
1238 [GNU_AK_ALIGNED] = "aligned",
1239 [GNU_AK_ALIAS] = "alias",
1240 [GNU_AK_SECTION] = "section",
1241 [GNU_AK_FORMAT] = "format",
1242 [GNU_AK_FORMAT_ARG] = "format_arg",
1243 [GNU_AK_WEAKREF] = "weakref",
1244 [GNU_AK_NONNULL] = "nonnull",
1245 [GNU_AK_TLS_MODEL] = "tls_model",
1246 [GNU_AK_VISIBILITY] = "visibility",
1247 [GNU_AK_REGPARM] = "regparm",
1248 [GNU_AK_MODE] = "mode",
1249 [GNU_AK_MODEL] = "model",
1250 [GNU_AK_TRAP_EXIT] = "trap_exit",
1251 [GNU_AK_SP_SWITCH] = "sp_switch",
1252 [GNU_AK_SENTINEL] = "sentinel"
1256 * compare two string, ignoring double underscores on the second.
1258 static int strcmp_underscore(const char *s1, const char *s2)
1260 if (s2[0] == '_' && s2[1] == '_') {
1261 size_t len2 = strlen(s2);
1262 size_t len1 = strlen(s1);
1263 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1264 return strncmp(s1, s2+2, len2-4);
1268 return strcmp(s1, s2);
1272 * Allocate a new gnu temporal attribute.
1274 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1276 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1277 attribute->kind = kind;
1278 attribute->next = NULL;
1279 attribute->invalid = false;
1280 attribute->have_arguments = false;
1286 * parse one constant expression argument.
1288 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1290 expression_t *expression;
1291 add_anchor_token(')');
1292 expression = parse_constant_expression();
1293 rem_anchor_token(')');
1295 attribute->u.argument = fold_constant(expression);
1298 attribute->invalid = true;
1302 * parse a list of constant expressions arguments.
1304 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1306 argument_list_t **list = &attribute->u.arguments;
1307 argument_list_t *entry;
1308 expression_t *expression;
1309 add_anchor_token(')');
1310 add_anchor_token(',');
1312 expression = parse_constant_expression();
1313 entry = obstack_alloc(&temp_obst, sizeof(entry));
1314 entry->argument = fold_constant(expression);
1317 list = &entry->next;
1318 if (token.type != ',')
1322 rem_anchor_token(',');
1323 rem_anchor_token(')');
1327 attribute->invalid = true;
1331 * parse one string literal argument.
1333 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1336 add_anchor_token('(');
1337 if (token.type != T_STRING_LITERAL) {
1338 parse_error_expected("while parsing attribute directive",
1339 T_STRING_LITERAL, NULL);
1342 *string = parse_string_literals();
1343 rem_anchor_token('(');
1347 attribute->invalid = true;
1351 * parse one tls model.
1353 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1355 static const char *const tls_models[] = {
1361 string_t string = { NULL, 0 };
1362 parse_gnu_attribute_string_arg(attribute, &string);
1363 if (string.begin != NULL) {
1364 for (size_t i = 0; i < 4; ++i) {
1365 if (strcmp(tls_models[i], string.begin) == 0) {
1366 attribute->u.value = i;
1370 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1372 attribute->invalid = true;
1376 * parse one tls model.
1378 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1380 static const char *const visibilities[] = {
1386 string_t string = { NULL, 0 };
1387 parse_gnu_attribute_string_arg(attribute, &string);
1388 if (string.begin != NULL) {
1389 for (size_t i = 0; i < 4; ++i) {
1390 if (strcmp(visibilities[i], string.begin) == 0) {
1391 attribute->u.value = i;
1395 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1397 attribute->invalid = true;
1401 * parse one (code) model.
1403 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1405 static const char *const visibilities[] = {
1410 string_t string = { NULL, 0 };
1411 parse_gnu_attribute_string_arg(attribute, &string);
1412 if (string.begin != NULL) {
1413 for (int i = 0; i < 3; ++i) {
1414 if (strcmp(visibilities[i], string.begin) == 0) {
1415 attribute->u.value = i;
1419 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1421 attribute->invalid = true;
1424 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1426 /* TODO: find out what is allowed here... */
1428 /* at least: byte, word, pointer, list of machine modes
1429 * __XXX___ is interpreted as XXX */
1430 add_anchor_token(')');
1432 if (token.type != T_IDENTIFIER) {
1433 expect(T_IDENTIFIER);
1436 /* This isn't really correct, the backend should provide a list of machine
1437 * specific modes (according to gcc philosophy that is...) */
1438 const char *symbol_str = token.v.symbol->string;
1439 if (strcmp_underscore("QI", symbol_str) == 0 ||
1440 strcmp_underscore("byte", symbol_str) == 0) {
1441 attribute->u.akind = ATOMIC_TYPE_CHAR;
1442 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1443 attribute->u.akind = ATOMIC_TYPE_SHORT;
1444 } else if (strcmp_underscore("SI", symbol_str) == 0
1445 || strcmp_underscore("word", symbol_str) == 0
1446 || strcmp_underscore("pointer", symbol_str) == 0) {
1447 attribute->u.akind = ATOMIC_TYPE_INT;
1448 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1449 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1452 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1453 attribute->invalid = true;
1457 rem_anchor_token(')');
1461 attribute->invalid = true;
1465 * parse one interrupt argument.
1467 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1469 static const char *const interrupts[] = {
1476 string_t string = { NULL, 0 };
1477 parse_gnu_attribute_string_arg(attribute, &string);
1478 if (string.begin != NULL) {
1479 for (size_t i = 0; i < 5; ++i) {
1480 if (strcmp(interrupts[i], string.begin) == 0) {
1481 attribute->u.value = i;
1485 errorf(HERE, "'%s' is not an interrupt", string.begin);
1487 attribute->invalid = true;
1491 * parse ( identifier, const expression, const expression )
1493 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1495 static const char *const format_names[] = {
1503 if (token.type != T_IDENTIFIER) {
1504 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1507 const char *name = token.v.symbol->string;
1508 for (i = 0; i < 4; ++i) {
1509 if (strcmp_underscore(format_names[i], name) == 0)
1513 if (warning.attribute)
1514 warningf(HERE, "'%s' is an unrecognized format function type", name);
1519 add_anchor_token(')');
1520 add_anchor_token(',');
1521 parse_constant_expression();
1522 rem_anchor_token(',');
1523 rem_anchor_token(')');
1526 add_anchor_token(')');
1527 parse_constant_expression();
1528 rem_anchor_token(')');
1532 attribute->u.value = true;
1535 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1537 if (!attribute->have_arguments)
1540 /* should have no arguments */
1541 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1542 eat_until_matching_token('(');
1543 /* we have already consumed '(', so we stop before ')', eat it */
1545 attribute->invalid = true;
1549 * Parse one GNU attribute.
1551 * Note that attribute names can be specified WITH or WITHOUT
1552 * double underscores, ie const or __const__.
1554 * The following attributes are parsed without arguments
1579 * no_instrument_function
1580 * warn_unused_result
1597 * externally_visible
1605 * The following attributes are parsed with arguments
1606 * aligned( const expression )
1607 * alias( string literal )
1608 * section( string literal )
1609 * format( identifier, const expression, const expression )
1610 * format_arg( const expression )
1611 * tls_model( string literal )
1612 * visibility( string literal )
1613 * regparm( const expression )
1614 * model( string leteral )
1615 * trap_exit( const expression )
1616 * sp_switch( string literal )
1618 * The following attributes might have arguments
1619 * weak_ref( string literal )
1620 * non_null( const expression // ',' )
1621 * interrupt( string literal )
1622 * sentinel( constant expression )
1624 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1626 gnu_attribute_t *head = *attributes;
1627 gnu_attribute_t *last = *attributes;
1628 decl_modifiers_t modifiers = 0;
1629 gnu_attribute_t *attribute;
1631 eat(T___attribute__);
1635 if (token.type != ')') {
1636 /* find the end of the list */
1638 while (last->next != NULL)
1642 /* non-empty attribute list */
1645 if (token.type == T_const) {
1647 } else if (token.type == T_volatile) {
1649 } else if (token.type == T_cdecl) {
1650 /* __attribute__((cdecl)), WITH ms mode */
1652 } else if (token.type == T_IDENTIFIER) {
1653 const symbol_t *sym = token.v.symbol;
1656 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1663 for (i = 0; i < GNU_AK_LAST; ++i) {
1664 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1667 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1670 if (kind == GNU_AK_LAST) {
1671 if (warning.attribute)
1672 warningf(HERE, "'%s' attribute directive ignored", name);
1674 /* skip possible arguments */
1675 if (token.type == '(') {
1676 eat_until_matching_token(')');
1679 /* check for arguments */
1680 attribute = allocate_gnu_attribute(kind);
1681 if (token.type == '(') {
1683 if (token.type == ')') {
1684 /* empty args are allowed */
1687 attribute->have_arguments = true;
1691 case GNU_AK_VOLATILE:
1696 case GNU_AK_NOCOMMON:
1698 case GNU_AK_NOTSHARED:
1699 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1700 case GNU_AK_WARN_UNUSED_RESULT:
1701 case GNU_AK_LONGCALL:
1702 case GNU_AK_SHORTCALL:
1703 case GNU_AK_LONG_CALL:
1704 case GNU_AK_SHORT_CALL:
1705 case GNU_AK_FUNCTION_VECTOR:
1706 case GNU_AK_INTERRUPT_HANDLER:
1707 case GNU_AK_NMI_HANDLER:
1708 case GNU_AK_NESTING:
1712 case GNU_AK_EIGTHBIT_DATA:
1713 case GNU_AK_TINY_DATA:
1714 case GNU_AK_SAVEALL:
1715 case GNU_AK_FLATTEN:
1716 case GNU_AK_SSEREGPARM:
1717 case GNU_AK_EXTERNALLY_VISIBLE:
1718 case GNU_AK_RETURN_TWICE:
1719 case GNU_AK_MAY_ALIAS:
1720 case GNU_AK_MS_STRUCT:
1721 case GNU_AK_GCC_STRUCT:
1724 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1725 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1726 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1727 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1728 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1729 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1730 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1731 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1732 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1733 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1734 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1735 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1736 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1737 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1738 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1739 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1740 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1741 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1743 case GNU_AK_ALIGNED:
1744 /* __align__ may be used without an argument */
1745 if (attribute->have_arguments) {
1746 parse_gnu_attribute_const_arg(attribute);
1750 case GNU_AK_FORMAT_ARG:
1751 case GNU_AK_REGPARM:
1752 case GNU_AK_TRAP_EXIT:
1753 if (!attribute->have_arguments) {
1754 /* should have arguments */
1755 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1756 attribute->invalid = true;
1758 parse_gnu_attribute_const_arg(attribute);
1761 case GNU_AK_SECTION:
1762 case GNU_AK_SP_SWITCH:
1763 if (!attribute->have_arguments) {
1764 /* should have arguments */
1765 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1766 attribute->invalid = true;
1768 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1771 if (!attribute->have_arguments) {
1772 /* should have arguments */
1773 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1774 attribute->invalid = true;
1776 parse_gnu_attribute_format_args(attribute);
1778 case GNU_AK_WEAKREF:
1779 /* may have one string argument */
1780 if (attribute->have_arguments)
1781 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1783 case GNU_AK_NONNULL:
1784 if (attribute->have_arguments)
1785 parse_gnu_attribute_const_arg_list(attribute);
1787 case GNU_AK_TLS_MODEL:
1788 if (!attribute->have_arguments) {
1789 /* should have arguments */
1790 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1792 parse_gnu_attribute_tls_model_arg(attribute);
1794 case GNU_AK_VISIBILITY:
1795 if (!attribute->have_arguments) {
1796 /* should have arguments */
1797 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1799 parse_gnu_attribute_visibility_arg(attribute);
1802 if (!attribute->have_arguments) {
1803 /* should have arguments */
1804 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1806 parse_gnu_attribute_model_arg(attribute);
1810 if (!attribute->have_arguments) {
1811 /* should have arguments */
1812 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1814 parse_gnu_attribute_mode_arg(attribute);
1817 case GNU_AK_INTERRUPT:
1818 /* may have one string argument */
1819 if (attribute->have_arguments)
1820 parse_gnu_attribute_interrupt_arg(attribute);
1822 case GNU_AK_SENTINEL:
1823 /* may have one string argument */
1824 if (attribute->have_arguments)
1825 parse_gnu_attribute_const_arg(attribute);
1828 /* already handled */
1832 check_no_argument(attribute, name);
1835 if (attribute != NULL) {
1837 last->next = attribute;
1840 head = last = attribute;
1844 if (token.type != ',')
1858 * Parse GNU attributes.
1860 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1862 decl_modifiers_t modifiers = 0;
1865 switch (token.type) {
1866 case T___attribute__:
1867 modifiers |= parse_gnu_attribute(attributes);
1873 if (token.type != T_STRING_LITERAL) {
1874 parse_error_expected("while parsing assembler attribute",
1875 T_STRING_LITERAL, NULL);
1876 eat_until_matching_token('(');
1879 parse_string_literals();
1884 case T_cdecl: modifiers |= DM_CDECL; break;
1885 case T__fastcall: modifiers |= DM_FASTCALL; break;
1886 case T__stdcall: modifiers |= DM_STDCALL; break;
1889 /* TODO record modifier */
1891 warningf(HERE, "Ignoring declaration modifier %K", &token);
1895 default: return modifiers;
1902 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1904 static variable_t *determine_lhs_var(expression_t *const expr,
1905 variable_t *lhs_var)
1907 switch (expr->kind) {
1908 case EXPR_REFERENCE: {
1909 entity_t *const entity = expr->reference.entity;
1910 /* we should only find variables as lavlues... */
1911 if (entity->base.kind != ENTITY_VARIABLE)
1914 return &entity->variable;
1917 case EXPR_ARRAY_ACCESS: {
1918 expression_t *const ref = expr->array_access.array_ref;
1919 variable_t * var = NULL;
1920 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1921 var = determine_lhs_var(ref, lhs_var);
1924 mark_vars_read(expr->select.compound, lhs_var);
1926 mark_vars_read(expr->array_access.index, lhs_var);
1931 if (is_type_compound(skip_typeref(expr->base.type))) {
1932 return determine_lhs_var(expr->select.compound, lhs_var);
1934 mark_vars_read(expr->select.compound, lhs_var);
1939 case EXPR_UNARY_DEREFERENCE: {
1940 expression_t *const val = expr->unary.value;
1941 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1943 return determine_lhs_var(val->unary.value, lhs_var);
1945 mark_vars_read(val, NULL);
1951 mark_vars_read(expr, NULL);
1956 #define VAR_ANY ((variable_t*)-1)
1959 * Mark declarations, which are read. This is used to deted variables, which
1963 * x is not marked as "read", because it is only read to calculate its own new
1967 * x and y are not detected as "not read", because multiple variables are
1970 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1972 switch (expr->kind) {
1973 case EXPR_REFERENCE: {
1974 entity_t *const entity = expr->reference.entity;
1975 if (entity->kind != ENTITY_VARIABLE)
1978 variable_t *variable = &entity->variable;
1979 if (lhs_var != variable && lhs_var != VAR_ANY) {
1980 variable->read = true;
1986 // TODO respect pure/const
1987 mark_vars_read(expr->call.function, NULL);
1988 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1989 mark_vars_read(arg->expression, NULL);
1993 case EXPR_CONDITIONAL:
1994 // TODO lhs_decl should depend on whether true/false have an effect
1995 mark_vars_read(expr->conditional.condition, NULL);
1996 if (expr->conditional.true_expression != NULL)
1997 mark_vars_read(expr->conditional.true_expression, lhs_var);
1998 mark_vars_read(expr->conditional.false_expression, lhs_var);
2002 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2004 mark_vars_read(expr->select.compound, lhs_var);
2007 case EXPR_ARRAY_ACCESS: {
2008 expression_t *const ref = expr->array_access.array_ref;
2009 mark_vars_read(ref, lhs_var);
2010 lhs_var = determine_lhs_var(ref, lhs_var);
2011 mark_vars_read(expr->array_access.index, lhs_var);
2016 mark_vars_read(expr->va_arge.ap, lhs_var);
2019 case EXPR_UNARY_CAST:
2020 /* Special case: Use void cast to mark a variable as "read" */
2021 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2026 case EXPR_UNARY_THROW:
2027 if (expr->unary.value == NULL)
2030 case EXPR_UNARY_DEREFERENCE:
2031 case EXPR_UNARY_DELETE:
2032 case EXPR_UNARY_DELETE_ARRAY:
2033 if (lhs_var == VAR_ANY)
2037 case EXPR_UNARY_NEGATE:
2038 case EXPR_UNARY_PLUS:
2039 case EXPR_UNARY_BITWISE_NEGATE:
2040 case EXPR_UNARY_NOT:
2041 case EXPR_UNARY_TAKE_ADDRESS:
2042 case EXPR_UNARY_POSTFIX_INCREMENT:
2043 case EXPR_UNARY_POSTFIX_DECREMENT:
2044 case EXPR_UNARY_PREFIX_INCREMENT:
2045 case EXPR_UNARY_PREFIX_DECREMENT:
2046 case EXPR_UNARY_CAST_IMPLICIT:
2047 case EXPR_UNARY_ASSUME:
2049 mark_vars_read(expr->unary.value, lhs_var);
2052 case EXPR_BINARY_ADD:
2053 case EXPR_BINARY_SUB:
2054 case EXPR_BINARY_MUL:
2055 case EXPR_BINARY_DIV:
2056 case EXPR_BINARY_MOD:
2057 case EXPR_BINARY_EQUAL:
2058 case EXPR_BINARY_NOTEQUAL:
2059 case EXPR_BINARY_LESS:
2060 case EXPR_BINARY_LESSEQUAL:
2061 case EXPR_BINARY_GREATER:
2062 case EXPR_BINARY_GREATEREQUAL:
2063 case EXPR_BINARY_BITWISE_AND:
2064 case EXPR_BINARY_BITWISE_OR:
2065 case EXPR_BINARY_BITWISE_XOR:
2066 case EXPR_BINARY_LOGICAL_AND:
2067 case EXPR_BINARY_LOGICAL_OR:
2068 case EXPR_BINARY_SHIFTLEFT:
2069 case EXPR_BINARY_SHIFTRIGHT:
2070 case EXPR_BINARY_COMMA:
2071 case EXPR_BINARY_ISGREATER:
2072 case EXPR_BINARY_ISGREATEREQUAL:
2073 case EXPR_BINARY_ISLESS:
2074 case EXPR_BINARY_ISLESSEQUAL:
2075 case EXPR_BINARY_ISLESSGREATER:
2076 case EXPR_BINARY_ISUNORDERED:
2077 mark_vars_read(expr->binary.left, lhs_var);
2078 mark_vars_read(expr->binary.right, lhs_var);
2081 case EXPR_BINARY_ASSIGN:
2082 case EXPR_BINARY_MUL_ASSIGN:
2083 case EXPR_BINARY_DIV_ASSIGN:
2084 case EXPR_BINARY_MOD_ASSIGN:
2085 case EXPR_BINARY_ADD_ASSIGN:
2086 case EXPR_BINARY_SUB_ASSIGN:
2087 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2088 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2089 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2090 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2091 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2092 if (lhs_var == VAR_ANY)
2094 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2095 mark_vars_read(expr->binary.right, lhs_var);
2100 determine_lhs_var(expr->va_starte.ap, lhs_var);
2106 case EXPR_CHARACTER_CONSTANT:
2107 case EXPR_WIDE_CHARACTER_CONSTANT:
2108 case EXPR_STRING_LITERAL:
2109 case EXPR_WIDE_STRING_LITERAL:
2110 case EXPR_COMPOUND_LITERAL: // TODO init?
2112 case EXPR_CLASSIFY_TYPE:
2115 case EXPR_BUILTIN_SYMBOL:
2116 case EXPR_BUILTIN_CONSTANT_P:
2117 case EXPR_BUILTIN_PREFETCH:
2119 case EXPR_STATEMENT: // TODO
2120 case EXPR_LABEL_ADDRESS:
2121 case EXPR_BINARY_BUILTIN_EXPECT:
2122 case EXPR_REFERENCE_ENUM_VALUE:
2126 panic("unhandled expression");
2129 static designator_t *parse_designation(void)
2131 designator_t *result = NULL;
2132 designator_t *last = NULL;
2135 designator_t *designator;
2136 switch (token.type) {
2138 designator = allocate_ast_zero(sizeof(designator[0]));
2139 designator->source_position = token.source_position;
2141 add_anchor_token(']');
2142 designator->array_index = parse_constant_expression();
2143 rem_anchor_token(']');
2147 designator = allocate_ast_zero(sizeof(designator[0]));
2148 designator->source_position = token.source_position;
2150 if (token.type != T_IDENTIFIER) {
2151 parse_error_expected("while parsing designator",
2152 T_IDENTIFIER, NULL);
2155 designator->symbol = token.v.symbol;
2163 assert(designator != NULL);
2165 last->next = designator;
2167 result = designator;
2175 static initializer_t *initializer_from_string(array_type_t *type,
2176 const string_t *const string)
2178 /* TODO: check len vs. size of array type */
2181 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2182 initializer->string.string = *string;
2187 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2188 wide_string_t *const string)
2190 /* TODO: check len vs. size of array type */
2193 initializer_t *const initializer =
2194 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2195 initializer->wide_string.string = *string;
2201 * Build an initializer from a given expression.
2203 static initializer_t *initializer_from_expression(type_t *orig_type,
2204 expression_t *expression)
2206 /* TODO check that expression is a constant expression */
2208 /* § 6.7.8.14/15 char array may be initialized by string literals */
2209 type_t *type = skip_typeref(orig_type);
2210 type_t *expr_type_orig = expression->base.type;
2211 type_t *expr_type = skip_typeref(expr_type_orig);
2212 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2213 array_type_t *const array_type = &type->array;
2214 type_t *const element_type = skip_typeref(array_type->element_type);
2216 if (element_type->kind == TYPE_ATOMIC) {
2217 atomic_type_kind_t akind = element_type->atomic.akind;
2218 switch (expression->kind) {
2219 case EXPR_STRING_LITERAL:
2220 if (akind == ATOMIC_TYPE_CHAR
2221 || akind == ATOMIC_TYPE_SCHAR
2222 || akind == ATOMIC_TYPE_UCHAR) {
2223 return initializer_from_string(array_type,
2224 &expression->string.value);
2227 case EXPR_WIDE_STRING_LITERAL: {
2228 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2229 if (get_unqualified_type(element_type) == bare_wchar_type) {
2230 return initializer_from_wide_string(array_type,
2231 &expression->wide_string.value);
2241 assign_error_t error = semantic_assign(type, expression);
2242 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2244 report_assign_error(error, type, expression, "initializer",
2245 &expression->base.source_position);
2247 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2249 if (type->kind == TYPE_BITFIELD) {
2250 type = type->bitfield.base_type;
2253 result->value.value = create_implicit_cast(expression, type);
2259 * Checks if a given expression can be used as an constant initializer.
2261 static bool is_initializer_constant(const expression_t *expression)
2263 return is_constant_expression(expression)
2264 || is_address_constant(expression);
2268 * Parses an scalar initializer.
2270 * § 6.7.8.11; eat {} without warning
2272 static initializer_t *parse_scalar_initializer(type_t *type,
2273 bool must_be_constant)
2275 /* there might be extra {} hierarchies */
2277 if (token.type == '{') {
2279 warningf(HERE, "extra curly braces around scalar initializer");
2283 } while (token.type == '{');
2286 expression_t *expression = parse_assignment_expression();
2287 mark_vars_read(expression, NULL);
2288 if (must_be_constant && !is_initializer_constant(expression)) {
2289 errorf(&expression->base.source_position,
2290 "Initialisation expression '%E' is not constant\n",
2294 initializer_t *initializer = initializer_from_expression(type, expression);
2296 if (initializer == NULL) {
2297 errorf(&expression->base.source_position,
2298 "expression '%E' (type '%T') doesn't match expected type '%T'",
2299 expression, expression->base.type, type);
2304 bool additional_warning_displayed = false;
2305 while (braces > 0) {
2306 if (token.type == ',') {
2309 if (token.type != '}') {
2310 if (!additional_warning_displayed && warning.other) {
2311 warningf(HERE, "additional elements in scalar initializer");
2312 additional_warning_displayed = true;
2323 * An entry in the type path.
2325 typedef struct type_path_entry_t type_path_entry_t;
2326 struct type_path_entry_t {
2327 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2329 size_t index; /**< For array types: the current index. */
2330 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2335 * A type path expression a position inside compound or array types.
2337 typedef struct type_path_t type_path_t;
2338 struct type_path_t {
2339 type_path_entry_t *path; /**< An flexible array containing the current path. */
2340 type_t *top_type; /**< type of the element the path points */
2341 size_t max_index; /**< largest index in outermost array */
2345 * Prints a type path for debugging.
2347 static __attribute__((unused)) void debug_print_type_path(
2348 const type_path_t *path)
2350 size_t len = ARR_LEN(path->path);
2352 for (size_t i = 0; i < len; ++i) {
2353 const type_path_entry_t *entry = & path->path[i];
2355 type_t *type = skip_typeref(entry->type);
2356 if (is_type_compound(type)) {
2357 /* in gcc mode structs can have no members */
2358 if (entry->v.compound_entry == NULL) {
2362 fprintf(stderr, ".%s",
2363 entry->v.compound_entry->base.symbol->string);
2364 } else if (is_type_array(type)) {
2365 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
2367 fprintf(stderr, "-INVALID-");
2370 if (path->top_type != NULL) {
2371 fprintf(stderr, " (");
2372 print_type(path->top_type);
2373 fprintf(stderr, ")");
2378 * Return the top type path entry, ie. in a path
2379 * (type).a.b returns the b.
2381 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2383 size_t len = ARR_LEN(path->path);
2385 return &path->path[len-1];
2389 * Enlarge the type path by an (empty) element.
2391 static type_path_entry_t *append_to_type_path(type_path_t *path)
2393 size_t len = ARR_LEN(path->path);
2394 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2396 type_path_entry_t *result = & path->path[len];
2397 memset(result, 0, sizeof(result[0]));
2402 * Descending into a sub-type. Enter the scope of the current top_type.
2404 static void descend_into_subtype(type_path_t *path)
2406 type_t *orig_top_type = path->top_type;
2407 type_t *top_type = skip_typeref(orig_top_type);
2409 type_path_entry_t *top = append_to_type_path(path);
2410 top->type = top_type;
2412 if (is_type_compound(top_type)) {
2413 compound_t *compound = top_type->compound.compound;
2414 entity_t *entry = compound->members.entities;
2416 if (entry != NULL) {
2417 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2418 top->v.compound_entry = &entry->declaration;
2419 path->top_type = entry->declaration.type;
2421 path->top_type = NULL;
2423 } else if (is_type_array(top_type)) {
2425 path->top_type = top_type->array.element_type;
2427 assert(!is_type_valid(top_type));
2432 * Pop an entry from the given type path, ie. returning from
2433 * (type).a.b to (type).a
2435 static void ascend_from_subtype(type_path_t *path)
2437 type_path_entry_t *top = get_type_path_top(path);
2439 path->top_type = top->type;
2441 size_t len = ARR_LEN(path->path);
2442 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2446 * Pop entries from the given type path until the given
2447 * path level is reached.
2449 static void ascend_to(type_path_t *path, size_t top_path_level)
2451 size_t len = ARR_LEN(path->path);
2453 while (len > top_path_level) {
2454 ascend_from_subtype(path);
2455 len = ARR_LEN(path->path);
2459 static bool walk_designator(type_path_t *path, const designator_t *designator,
2460 bool used_in_offsetof)
2462 for (; designator != NULL; designator = designator->next) {
2463 type_path_entry_t *top = get_type_path_top(path);
2464 type_t *orig_type = top->type;
2466 type_t *type = skip_typeref(orig_type);
2468 if (designator->symbol != NULL) {
2469 symbol_t *symbol = designator->symbol;
2470 if (!is_type_compound(type)) {
2471 if (is_type_valid(type)) {
2472 errorf(&designator->source_position,
2473 "'.%Y' designator used for non-compound type '%T'",
2477 top->type = type_error_type;
2478 top->v.compound_entry = NULL;
2479 orig_type = type_error_type;
2481 compound_t *compound = type->compound.compound;
2482 entity_t *iter = compound->members.entities;
2483 for (; iter != NULL; iter = iter->base.next) {
2484 if (iter->base.symbol == symbol) {
2489 errorf(&designator->source_position,
2490 "'%T' has no member named '%Y'", orig_type, symbol);
2493 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2494 if (used_in_offsetof) {
2495 type_t *real_type = skip_typeref(iter->declaration.type);
2496 if (real_type->kind == TYPE_BITFIELD) {
2497 errorf(&designator->source_position,
2498 "offsetof designator '%Y' may not specify bitfield",
2504 top->type = orig_type;
2505 top->v.compound_entry = &iter->declaration;
2506 orig_type = iter->declaration.type;
2509 expression_t *array_index = designator->array_index;
2510 assert(designator->array_index != NULL);
2512 if (!is_type_array(type)) {
2513 if (is_type_valid(type)) {
2514 errorf(&designator->source_position,
2515 "[%E] designator used for non-array type '%T'",
2516 array_index, orig_type);
2521 long index = fold_constant(array_index);
2522 if (!used_in_offsetof) {
2524 errorf(&designator->source_position,
2525 "array index [%E] must be positive", array_index);
2526 } else if (type->array.size_constant) {
2527 long array_size = type->array.size;
2528 if (index >= array_size) {
2529 errorf(&designator->source_position,
2530 "designator [%E] (%d) exceeds array size %d",
2531 array_index, index, array_size);
2536 top->type = orig_type;
2537 top->v.index = (size_t) index;
2538 orig_type = type->array.element_type;
2540 path->top_type = orig_type;
2542 if (designator->next != NULL) {
2543 descend_into_subtype(path);
2552 static void advance_current_object(type_path_t *path, size_t top_path_level)
2554 type_path_entry_t *top = get_type_path_top(path);
2556 type_t *type = skip_typeref(top->type);
2557 if (is_type_union(type)) {
2558 /* in unions only the first element is initialized */
2559 top->v.compound_entry = NULL;
2560 } else if (is_type_struct(type)) {
2561 declaration_t *entry = top->v.compound_entry;
2563 entity_t *next_entity = entry->base.next;
2564 if (next_entity != NULL) {
2565 assert(is_declaration(next_entity));
2566 entry = &next_entity->declaration;
2571 top->v.compound_entry = entry;
2572 if (entry != NULL) {
2573 path->top_type = entry->type;
2576 } else if (is_type_array(type)) {
2577 assert(is_type_array(type));
2581 if (!type->array.size_constant || top->v.index < type->array.size) {
2585 assert(!is_type_valid(type));
2589 /* we're past the last member of the current sub-aggregate, try if we
2590 * can ascend in the type hierarchy and continue with another subobject */
2591 size_t len = ARR_LEN(path->path);
2593 if (len > top_path_level) {
2594 ascend_from_subtype(path);
2595 advance_current_object(path, top_path_level);
2597 path->top_type = NULL;
2602 * skip until token is found.
2604 static void skip_until(int type)
2606 while (token.type != type) {
2607 if (token.type == T_EOF)
2614 * skip any {...} blocks until a closing bracket is reached.
2616 static void skip_initializers(void)
2618 if (token.type == '{')
2621 while (token.type != '}') {
2622 if (token.type == T_EOF)
2624 if (token.type == '{') {
2632 static initializer_t *create_empty_initializer(void)
2634 static initializer_t empty_initializer
2635 = { .list = { { INITIALIZER_LIST }, 0 } };
2636 return &empty_initializer;
2640 * Parse a part of an initialiser for a struct or union,
2642 static initializer_t *parse_sub_initializer(type_path_t *path,
2643 type_t *outer_type, size_t top_path_level,
2644 parse_initializer_env_t *env)
2646 if (token.type == '}') {
2647 /* empty initializer */
2648 return create_empty_initializer();
2651 type_t *orig_type = path->top_type;
2652 type_t *type = NULL;
2654 if (orig_type == NULL) {
2655 /* We are initializing an empty compound. */
2657 type = skip_typeref(orig_type);
2660 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2663 designator_t *designator = NULL;
2664 if (token.type == '.' || token.type == '[') {
2665 designator = parse_designation();
2666 goto finish_designator;
2667 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2668 /* GNU-style designator ("identifier: value") */
2669 designator = allocate_ast_zero(sizeof(designator[0]));
2670 designator->source_position = token.source_position;
2671 designator->symbol = token.v.symbol;
2676 /* reset path to toplevel, evaluate designator from there */
2677 ascend_to(path, top_path_level);
2678 if (!walk_designator(path, designator, false)) {
2679 /* can't continue after designation error */
2683 initializer_t *designator_initializer
2684 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2685 designator_initializer->designator.designator = designator;
2686 ARR_APP1(initializer_t*, initializers, designator_initializer);
2688 orig_type = path->top_type;
2689 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2694 if (token.type == '{') {
2695 if (type != NULL && is_type_scalar(type)) {
2696 sub = parse_scalar_initializer(type, env->must_be_constant);
2700 if (env->entity != NULL) {
2702 "extra brace group at end of initializer for '%Y'",
2703 env->entity->base.symbol);
2705 errorf(HERE, "extra brace group at end of initializer");
2708 descend_into_subtype(path);
2710 add_anchor_token('}');
2711 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2713 rem_anchor_token('}');
2716 ascend_from_subtype(path);
2720 goto error_parse_next;
2724 /* must be an expression */
2725 expression_t *expression = parse_assignment_expression();
2727 if (env->must_be_constant && !is_initializer_constant(expression)) {
2728 errorf(&expression->base.source_position,
2729 "Initialisation expression '%E' is not constant\n",
2734 /* we are already outside, ... */
2735 type_t *const outer_type_skip = skip_typeref(outer_type);
2736 if (is_type_compound(outer_type_skip) &&
2737 !outer_type_skip->compound.compound->complete) {
2738 goto error_parse_next;
2743 /* handle { "string" } special case */
2744 if ((expression->kind == EXPR_STRING_LITERAL
2745 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2746 && outer_type != NULL) {
2747 sub = initializer_from_expression(outer_type, expression);
2749 if (token.type == ',') {
2752 if (token.type != '}' && warning.other) {
2753 warningf(HERE, "excessive elements in initializer for type '%T'",
2756 /* TODO: eat , ... */
2761 /* descend into subtypes until expression matches type */
2763 orig_type = path->top_type;
2764 type = skip_typeref(orig_type);
2766 sub = initializer_from_expression(orig_type, expression);
2770 if (!is_type_valid(type)) {
2773 if (is_type_scalar(type)) {
2774 errorf(&expression->base.source_position,
2775 "expression '%E' doesn't match expected type '%T'",
2776 expression, orig_type);
2780 descend_into_subtype(path);
2784 /* update largest index of top array */
2785 const type_path_entry_t *first = &path->path[0];
2786 type_t *first_type = first->type;
2787 first_type = skip_typeref(first_type);
2788 if (is_type_array(first_type)) {
2789 size_t index = first->v.index;
2790 if (index > path->max_index)
2791 path->max_index = index;
2795 /* append to initializers list */
2796 ARR_APP1(initializer_t*, initializers, sub);
2799 if (warning.other) {
2800 if (env->entity != NULL) {
2801 warningf(HERE, "excess elements in struct initializer for '%Y'",
2802 env->entity->base.symbol);
2804 warningf(HERE, "excess elements in struct initializer");
2810 if (token.type == '}') {
2814 if (token.type == '}') {
2819 /* advance to the next declaration if we are not at the end */
2820 advance_current_object(path, top_path_level);
2821 orig_type = path->top_type;
2822 if (orig_type != NULL)
2823 type = skip_typeref(orig_type);
2829 size_t len = ARR_LEN(initializers);
2830 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2831 initializer_t *result = allocate_ast_zero(size);
2832 result->kind = INITIALIZER_LIST;
2833 result->list.len = len;
2834 memcpy(&result->list.initializers, initializers,
2835 len * sizeof(initializers[0]));
2837 DEL_ARR_F(initializers);
2838 ascend_to(path, top_path_level+1);
2843 skip_initializers();
2844 DEL_ARR_F(initializers);
2845 ascend_to(path, top_path_level+1);
2850 * Parses an initializer. Parsers either a compound literal
2851 * (env->declaration == NULL) or an initializer of a declaration.
2853 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2855 type_t *type = skip_typeref(env->type);
2856 initializer_t *result = NULL;
2859 if (is_type_scalar(type)) {
2860 result = parse_scalar_initializer(type, env->must_be_constant);
2861 } else if (token.type == '{') {
2865 memset(&path, 0, sizeof(path));
2866 path.top_type = env->type;
2867 path.path = NEW_ARR_F(type_path_entry_t, 0);
2869 descend_into_subtype(&path);
2871 add_anchor_token('}');
2872 result = parse_sub_initializer(&path, env->type, 1, env);
2873 rem_anchor_token('}');
2875 max_index = path.max_index;
2876 DEL_ARR_F(path.path);
2880 /* parse_scalar_initializer() also works in this case: we simply
2881 * have an expression without {} around it */
2882 result = parse_scalar_initializer(type, env->must_be_constant);
2885 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2886 * the array type size */
2887 if (is_type_array(type) && type->array.size_expression == NULL
2888 && result != NULL) {
2890 switch (result->kind) {
2891 case INITIALIZER_LIST:
2892 size = max_index + 1;
2895 case INITIALIZER_STRING:
2896 size = result->string.string.size;
2899 case INITIALIZER_WIDE_STRING:
2900 size = result->wide_string.string.size;
2903 case INITIALIZER_DESIGNATOR:
2904 case INITIALIZER_VALUE:
2905 /* can happen for parse errors */
2910 internal_errorf(HERE, "invalid initializer type");
2913 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2914 cnst->base.type = type_size_t;
2915 cnst->conste.v.int_value = size;
2917 type_t *new_type = duplicate_type(type);
2919 new_type->array.size_expression = cnst;
2920 new_type->array.size_constant = true;
2921 new_type->array.has_implicit_size = true;
2922 new_type->array.size = size;
2923 env->type = new_type;
2931 static void append_entity(scope_t *scope, entity_t *entity)
2933 if (scope->last_entity != NULL) {
2934 scope->last_entity->base.next = entity;
2936 scope->entities = entity;
2938 scope->last_entity = entity;
2942 static compound_t *parse_compound_type_specifier(bool is_struct)
2944 gnu_attribute_t *attributes = NULL;
2945 decl_modifiers_t modifiers = 0;
2952 symbol_t *symbol = NULL;
2953 compound_t *compound = NULL;
2955 if (token.type == T___attribute__) {
2956 modifiers |= parse_attributes(&attributes);
2959 if (token.type == T_IDENTIFIER) {
2960 symbol = token.v.symbol;
2963 namespace_tag_t const namespc =
2964 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2965 entity_t *entity = get_entity(symbol, namespc);
2966 if (entity != NULL) {
2967 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2968 compound = &entity->compound;
2969 if (compound->base.parent_scope != current_scope &&
2970 (token.type == '{' || token.type == ';')) {
2971 /* we're in an inner scope and have a definition. Override
2972 existing definition in outer scope */
2974 } else if (compound->complete && token.type == '{') {
2975 assert(symbol != NULL);
2976 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2977 is_struct ? "struct" : "union", symbol,
2978 &compound->base.source_position);
2979 /* clear members in the hope to avoid further errors */
2980 compound->members.entities = NULL;
2983 } else if (token.type != '{') {
2985 parse_error_expected("while parsing struct type specifier",
2986 T_IDENTIFIER, '{', NULL);
2988 parse_error_expected("while parsing union type specifier",
2989 T_IDENTIFIER, '{', NULL);
2995 if (compound == NULL) {
2996 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2997 entity_t *entity = allocate_entity_zero(kind);
2998 compound = &entity->compound;
3000 compound->base.namespc =
3001 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3002 compound->base.source_position = token.source_position;
3003 compound->base.symbol = symbol;
3004 compound->base.parent_scope = current_scope;
3005 if (symbol != NULL) {
3006 environment_push(entity);
3008 append_entity(current_scope, entity);
3011 if (token.type == '{') {
3012 parse_compound_type_entries(compound);
3013 modifiers |= parse_attributes(&attributes);
3015 if (symbol == NULL) {
3016 assert(anonymous_entity == NULL);
3017 anonymous_entity = (entity_t*)compound;
3021 compound->modifiers |= modifiers;
3025 static void parse_enum_entries(type_t *const enum_type)
3029 if (token.type == '}') {
3030 errorf(HERE, "empty enum not allowed");
3035 add_anchor_token('}');
3037 if (token.type != T_IDENTIFIER) {
3038 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3040 rem_anchor_token('}');
3044 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3045 entity->enum_value.enum_type = enum_type;
3046 entity->base.symbol = token.v.symbol;
3047 entity->base.source_position = token.source_position;
3050 if (token.type == '=') {
3052 expression_t *value = parse_constant_expression();
3054 value = create_implicit_cast(value, enum_type);
3055 entity->enum_value.value = value;
3060 record_entity(entity, false);
3062 if (token.type != ',')
3065 } while (token.type != '}');
3066 rem_anchor_token('}');
3074 static type_t *parse_enum_specifier(void)
3076 gnu_attribute_t *attributes = NULL;
3081 if (token.type == T_IDENTIFIER) {
3082 symbol = token.v.symbol;
3085 entity = get_entity(symbol, NAMESPACE_ENUM);
3086 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3087 } else if (token.type != '{') {
3088 parse_error_expected("while parsing enum type specifier",
3089 T_IDENTIFIER, '{', NULL);
3096 if (entity == NULL) {
3097 entity = allocate_entity_zero(ENTITY_ENUM);
3098 entity->base.namespc = NAMESPACE_ENUM;
3099 entity->base.source_position = token.source_position;
3100 entity->base.symbol = symbol;
3101 entity->base.parent_scope = current_scope;
3104 type_t *const type = allocate_type_zero(TYPE_ENUM);
3105 type->enumt.enume = &entity->enume;
3107 if (token.type == '{') {
3108 if (entity->enume.complete) {
3109 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3110 symbol, &entity->base.source_position);
3112 if (symbol != NULL) {
3113 environment_push(entity);
3115 append_entity(current_scope, entity);
3116 entity->enume.complete = true;
3118 parse_enum_entries(type);
3119 parse_attributes(&attributes);
3121 if (symbol == NULL) {
3122 assert(anonymous_entity == NULL);
3123 anonymous_entity = entity;
3125 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
3126 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3134 * if a symbol is a typedef to another type, return true
3136 static bool is_typedef_symbol(symbol_t *symbol)
3138 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3139 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3142 static type_t *parse_typeof(void)
3149 add_anchor_token(')');
3151 expression_t *expression = NULL;
3153 bool old_type_prop = in_type_prop;
3154 bool old_gcc_extension = in_gcc_extension;
3155 in_type_prop = true;
3157 while (token.type == T___extension__) {
3158 /* This can be a prefix to a typename or an expression. */
3160 in_gcc_extension = true;
3162 switch (token.type) {
3164 if (is_typedef_symbol(token.v.symbol)) {
3165 type = parse_typename();
3167 expression = parse_expression();
3168 type = expression->base.type;
3173 type = parse_typename();
3177 expression = parse_expression();
3178 type = expression->base.type;
3181 in_type_prop = old_type_prop;
3182 in_gcc_extension = old_gcc_extension;
3184 rem_anchor_token(')');
3187 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3188 typeof_type->typeoft.expression = expression;
3189 typeof_type->typeoft.typeof_type = type;
3196 typedef enum specifiers_t {
3197 SPECIFIER_SIGNED = 1 << 0,
3198 SPECIFIER_UNSIGNED = 1 << 1,
3199 SPECIFIER_LONG = 1 << 2,
3200 SPECIFIER_INT = 1 << 3,
3201 SPECIFIER_DOUBLE = 1 << 4,
3202 SPECIFIER_CHAR = 1 << 5,
3203 SPECIFIER_SHORT = 1 << 6,
3204 SPECIFIER_LONG_LONG = 1 << 7,
3205 SPECIFIER_FLOAT = 1 << 8,
3206 SPECIFIER_BOOL = 1 << 9,
3207 SPECIFIER_VOID = 1 << 10,
3208 SPECIFIER_INT8 = 1 << 11,
3209 SPECIFIER_INT16 = 1 << 12,
3210 SPECIFIER_INT32 = 1 << 13,
3211 SPECIFIER_INT64 = 1 << 14,
3212 SPECIFIER_INT128 = 1 << 15,
3213 SPECIFIER_COMPLEX = 1 << 16,
3214 SPECIFIER_IMAGINARY = 1 << 17,
3217 static type_t *create_builtin_type(symbol_t *const symbol,
3218 type_t *const real_type)
3220 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3221 type->builtin.symbol = symbol;
3222 type->builtin.real_type = real_type;
3224 type_t *result = typehash_insert(type);
3225 if (type != result) {
3232 static type_t *get_typedef_type(symbol_t *symbol)
3234 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3235 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3238 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3239 type->typedeft.typedefe = &entity->typedefe;
3245 * check for the allowed MS alignment values.
3247 static bool check_alignment_value(long long intvalue)
3249 if (intvalue < 1 || intvalue > 8192) {
3250 errorf(HERE, "illegal alignment value");
3253 unsigned v = (unsigned)intvalue;
3254 for (unsigned i = 1; i <= 8192; i += i) {
3258 errorf(HERE, "alignment must be power of two");
3262 #define DET_MOD(name, tag) do { \
3263 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3264 *modifiers |= tag; \
3267 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3269 decl_modifiers_t *modifiers = &specifiers->modifiers;
3272 if (token.type == T_restrict) {
3274 DET_MOD(restrict, DM_RESTRICT);
3276 } else if (token.type != T_IDENTIFIER)
3278 symbol_t *symbol = token.v.symbol;
3279 if (symbol == sym_align) {
3282 if (token.type != T_INTEGER)
3284 if (check_alignment_value(token.v.intvalue)) {
3285 if (specifiers->alignment != 0 && warning.other)
3286 warningf(HERE, "align used more than once");
3287 specifiers->alignment = (unsigned char)token.v.intvalue;
3291 } else if (symbol == sym_allocate) {
3294 if (token.type != T_IDENTIFIER)
3296 (void)token.v.symbol;
3298 } else if (symbol == sym_dllimport) {
3300 DET_MOD(dllimport, DM_DLLIMPORT);
3301 } else if (symbol == sym_dllexport) {
3303 DET_MOD(dllexport, DM_DLLEXPORT);
3304 } else if (symbol == sym_thread) {
3306 DET_MOD(thread, DM_THREAD);
3307 } else if (symbol == sym_naked) {
3309 DET_MOD(naked, DM_NAKED);
3310 } else if (symbol == sym_noinline) {
3312 DET_MOD(noinline, DM_NOINLINE);
3313 } else if (symbol == sym_noreturn) {
3315 DET_MOD(noreturn, DM_NORETURN);
3316 } else if (symbol == sym_nothrow) {
3318 DET_MOD(nothrow, DM_NOTHROW);
3319 } else if (symbol == sym_novtable) {
3321 DET_MOD(novtable, DM_NOVTABLE);
3322 } else if (symbol == sym_property) {
3326 bool is_get = false;
3327 if (token.type != T_IDENTIFIER)
3329 if (token.v.symbol == sym_get) {
3331 } else if (token.v.symbol == sym_put) {
3333 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3338 if (token.type != T_IDENTIFIER)
3341 if (specifiers->get_property_sym != NULL) {
3342 errorf(HERE, "get property name already specified");
3344 specifiers->get_property_sym = token.v.symbol;
3347 if (specifiers->put_property_sym != NULL) {
3348 errorf(HERE, "put property name already specified");
3350 specifiers->put_property_sym = token.v.symbol;
3354 if (token.type == ',') {
3361 } else if (symbol == sym_selectany) {
3363 DET_MOD(selectany, DM_SELECTANY);
3364 } else if (symbol == sym_uuid) {
3367 if (token.type != T_STRING_LITERAL)
3371 } else if (symbol == sym_deprecated) {
3373 if (specifiers->deprecated != 0 && warning.other)
3374 warningf(HERE, "deprecated used more than once");
3375 specifiers->deprecated = true;
3376 if (token.type == '(') {
3378 if (token.type == T_STRING_LITERAL) {
3379 specifiers->deprecated_string = token.v.string.begin;
3382 errorf(HERE, "string literal expected");
3386 } else if (symbol == sym_noalias) {
3388 DET_MOD(noalias, DM_NOALIAS);
3391 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3393 if (token.type == '(')
3397 if (token.type == ',')
3404 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3406 entity_t *entity = allocate_entity_zero(kind);
3407 entity->base.source_position = *HERE;
3408 entity->base.symbol = symbol;
3409 if (is_declaration(entity)) {
3410 entity->declaration.type = type_error_type;
3411 entity->declaration.implicit = true;
3412 } else if (kind == ENTITY_TYPEDEF) {
3413 entity->typedefe.type = type_error_type;
3415 record_entity(entity, false);
3419 static void parse_microsoft_based(based_spec_t *based_spec)
3421 if (token.type != T_IDENTIFIER) {
3422 parse_error_expected("while parsing __based", T_IDENTIFIER, NULL);
3425 symbol_t *symbol = token.v.symbol;
3426 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3428 if (entity == NULL || entity->base.kind != ENTITY_VARIABLE) {
3429 errorf(HERE, "'%Y' is not a variable name.", symbol);
3430 entity = create_error_entity(symbol, ENTITY_VARIABLE);
3432 variable_t *variable = &entity->variable;
3434 if (based_spec->base_variable != NULL) {
3435 errorf(HERE, "__based type qualifier specified more than once");
3437 based_spec->source_position = token.source_position;
3438 based_spec->base_variable = variable;
3440 type_t *const type = variable->base.type;
3442 if (is_type_valid(type)) {
3443 if (! is_type_pointer(skip_typeref(type))) {
3444 errorf(HERE, "variable in __based modifier must have pointer type instead of %T", type);
3446 if (variable->base.base.parent_scope != file_scope) {
3447 errorf(HERE, "a nonstatic local variable may not be used in a __based specification");
3455 * Finish the construction of a struct type by calculating
3456 * its size, offsets, alignment.
3458 static void finish_struct_type(compound_type_t *type)
3460 assert(type->compound != NULL);
3462 compound_t *compound = type->compound;
3463 if (!compound->complete)
3468 il_alignment_t alignment = 1;
3469 bool need_pad = false;
3471 entity_t *entry = compound->members.entities;
3472 for (; entry != NULL; entry = entry->base.next) {
3473 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3476 type_t *m_type = skip_typeref(entry->declaration.type);
3477 if (! is_type_valid(m_type)) {
3478 /* simply ignore errors here */
3481 il_alignment_t m_alignment = m_type->base.alignment;
3482 if (m_alignment > alignment)
3483 alignment = m_alignment;
3485 offset = (size + m_alignment - 1) & -m_alignment;
3489 entry->compound_member.offset = offset;
3490 size = offset + m_type->base.size;
3492 if (type->base.alignment != 0) {
3493 alignment = type->base.alignment;
3496 offset = (size + alignment - 1) & -alignment;
3500 if (warning.padded && need_pad) {
3501 warningf(&compound->base.source_position,
3502 "'%#T' needs padding", type, compound->base.symbol);
3504 if (warning.packed && !need_pad) {
3505 warningf(&compound->base.source_position,
3506 "superfluous packed attribute on '%#T'",
3507 type, compound->base.symbol);
3510 type->base.size = offset;
3511 type->base.alignment = alignment;
3515 * Finish the construction of an union type by calculating
3516 * its size and alignment.
3518 static void finish_union_type(compound_type_t *type)
3520 assert(type->compound != NULL);
3522 compound_t *compound = type->compound;
3523 if (! compound->complete)
3527 il_alignment_t alignment = 1;
3529 entity_t *entry = compound->members.entities;
3530 for (; entry != NULL; entry = entry->base.next) {
3531 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3534 type_t *m_type = skip_typeref(entry->declaration.type);
3535 if (! is_type_valid(m_type))
3538 entry->compound_member.offset = 0;
3539 if (m_type->base.size > size)
3540 size = m_type->base.size;
3541 if (m_type->base.alignment > alignment)
3542 alignment = m_type->base.alignment;
3544 if (type->base.alignment != 0) {
3545 alignment = type->base.alignment;
3547 size = (size + alignment - 1) & -alignment;
3548 type->base.size = size;
3549 type->base.alignment = alignment;
3552 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3554 type_t *type = NULL;
3555 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3556 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3557 unsigned type_specifiers = 0;
3558 bool newtype = false;
3559 bool saw_error = false;
3560 bool old_gcc_extension = in_gcc_extension;
3562 specifiers->source_position = token.source_position;
3565 specifiers->modifiers
3566 |= parse_attributes(&specifiers->gnu_attributes);
3567 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3568 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3570 switch (token.type) {
3573 #define MATCH_STORAGE_CLASS(token, class) \
3575 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3576 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3578 specifiers->storage_class = class; \
3582 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3583 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3584 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3585 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3586 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3591 add_anchor_token(')');
3592 parse_microsoft_extended_decl_modifier(specifiers);
3593 rem_anchor_token(')');
3598 switch (specifiers->storage_class) {
3599 case STORAGE_CLASS_NONE:
3600 specifiers->storage_class = STORAGE_CLASS_THREAD;
3603 case STORAGE_CLASS_EXTERN:
3604 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3607 case STORAGE_CLASS_STATIC:
3608 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3612 errorf(HERE, "multiple storage classes in declaration specifiers");
3618 /* type qualifiers */
3619 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3621 qualifiers |= qualifier; \
3625 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3626 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3627 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3628 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3629 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3630 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3631 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3632 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3634 case T___extension__:
3636 in_gcc_extension = true;
3639 /* type specifiers */
3640 #define MATCH_SPECIFIER(token, specifier, name) \
3642 if (type_specifiers & specifier) { \
3643 errorf(HERE, "multiple " name " type specifiers given"); \
3645 type_specifiers |= specifier; \
3650 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3651 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3652 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3653 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3654 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3655 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3656 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3657 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3658 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3659 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3660 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3661 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3662 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3663 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3664 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3665 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3666 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3668 case T__forceinline:
3669 /* only in microsoft mode */
3670 specifiers->modifiers |= DM_FORCEINLINE;
3675 specifiers->is_inline = true;
3679 if (type_specifiers & SPECIFIER_LONG_LONG) {
3680 errorf(HERE, "multiple type specifiers given");
3681 } else if (type_specifiers & SPECIFIER_LONG) {
3682 type_specifiers |= SPECIFIER_LONG_LONG;
3684 type_specifiers |= SPECIFIER_LONG;
3690 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3692 type->compound.compound = parse_compound_type_specifier(true);
3693 finish_struct_type(&type->compound);
3697 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3698 type->compound.compound = parse_compound_type_specifier(false);
3699 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3700 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3701 finish_union_type(&type->compound);
3705 type = parse_enum_specifier();
3708 type = parse_typeof();
3710 case T___builtin_va_list:
3711 type = duplicate_type(type_valist);
3715 case T_IDENTIFIER: {
3716 /* only parse identifier if we haven't found a type yet */
3717 if (type != NULL || type_specifiers != 0) {
3718 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3719 * declaration, so it doesn't generate errors about expecting '(' or
3721 switch (look_ahead(1)->type) {
3728 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3732 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3737 goto finish_specifiers;
3741 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3742 if (typedef_type == NULL) {
3743 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3744 * declaration, so it doesn't generate 'implicit int' followed by more
3745 * errors later on. */
3746 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3752 errorf(HERE, "%K does not name a type", &token);
3755 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3757 type = allocate_type_zero(TYPE_TYPEDEF);
3758 type->typedeft.typedefe = &entity->typedefe;
3762 if (la1_type == '&' || la1_type == '*')
3763 goto finish_specifiers;
3768 goto finish_specifiers;
3773 type = typedef_type;
3777 /* function specifier */
3779 goto finish_specifiers;
3784 in_gcc_extension = old_gcc_extension;
3786 if (type == NULL || (saw_error && type_specifiers != 0)) {
3787 atomic_type_kind_t atomic_type;
3789 /* match valid basic types */
3790 switch (type_specifiers) {
3791 case SPECIFIER_VOID:
3792 atomic_type = ATOMIC_TYPE_VOID;
3794 case SPECIFIER_CHAR:
3795 atomic_type = ATOMIC_TYPE_CHAR;
3797 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3798 atomic_type = ATOMIC_TYPE_SCHAR;
3800 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3801 atomic_type = ATOMIC_TYPE_UCHAR;
3803 case SPECIFIER_SHORT:
3804 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3805 case SPECIFIER_SHORT | SPECIFIER_INT:
3806 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3807 atomic_type = ATOMIC_TYPE_SHORT;
3809 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3810 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3811 atomic_type = ATOMIC_TYPE_USHORT;
3814 case SPECIFIER_SIGNED:
3815 case SPECIFIER_SIGNED | SPECIFIER_INT:
3816 atomic_type = ATOMIC_TYPE_INT;
3818 case SPECIFIER_UNSIGNED:
3819 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3820 atomic_type = ATOMIC_TYPE_UINT;
3822 case SPECIFIER_LONG:
3823 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3824 case SPECIFIER_LONG | SPECIFIER_INT:
3825 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3826 atomic_type = ATOMIC_TYPE_LONG;
3828 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3829 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3830 atomic_type = ATOMIC_TYPE_ULONG;
3833 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3834 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3835 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3836 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3838 atomic_type = ATOMIC_TYPE_LONGLONG;
3839 goto warn_about_long_long;
3841 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3842 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3844 atomic_type = ATOMIC_TYPE_ULONGLONG;
3845 warn_about_long_long:
3846 if (warning.long_long) {
3847 warningf(&specifiers->source_position,
3848 "ISO C90 does not support 'long long'");
3852 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3853 atomic_type = unsigned_int8_type_kind;
3856 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3857 atomic_type = unsigned_int16_type_kind;
3860 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3861 atomic_type = unsigned_int32_type_kind;
3864 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3865 atomic_type = unsigned_int64_type_kind;
3868 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3869 atomic_type = unsigned_int128_type_kind;
3872 case SPECIFIER_INT8:
3873 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3874 atomic_type = int8_type_kind;
3877 case SPECIFIER_INT16:
3878 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3879 atomic_type = int16_type_kind;
3882 case SPECIFIER_INT32:
3883 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3884 atomic_type = int32_type_kind;
3887 case SPECIFIER_INT64:
3888 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3889 atomic_type = int64_type_kind;
3892 case SPECIFIER_INT128:
3893 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3894 atomic_type = int128_type_kind;
3897 case SPECIFIER_FLOAT:
3898 atomic_type = ATOMIC_TYPE_FLOAT;
3900 case SPECIFIER_DOUBLE:
3901 atomic_type = ATOMIC_TYPE_DOUBLE;
3903 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3904 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3906 case SPECIFIER_BOOL:
3907 atomic_type = ATOMIC_TYPE_BOOL;
3909 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3910 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3911 atomic_type = ATOMIC_TYPE_FLOAT;
3913 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3914 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3915 atomic_type = ATOMIC_TYPE_DOUBLE;
3917 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3918 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3919 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3922 /* invalid specifier combination, give an error message */
3923 if (type_specifiers == 0) {
3927 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3928 if (!(c_mode & _CXX) && !strict_mode) {
3929 if (warning.implicit_int) {
3930 warningf(HERE, "no type specifiers in declaration, using 'int'");
3932 atomic_type = ATOMIC_TYPE_INT;
3935 errorf(HERE, "no type specifiers given in declaration");
3937 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3938 (type_specifiers & SPECIFIER_UNSIGNED)) {
3939 errorf(HERE, "signed and unsigned specifiers given");
3940 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3941 errorf(HERE, "only integer types can be signed or unsigned");
3943 errorf(HERE, "multiple datatypes in declaration");
3948 if (type_specifiers & SPECIFIER_COMPLEX) {
3949 type = allocate_type_zero(TYPE_COMPLEX);
3950 type->complex.akind = atomic_type;
3951 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3952 type = allocate_type_zero(TYPE_IMAGINARY);
3953 type->imaginary.akind = atomic_type;
3955 type = allocate_type_zero(TYPE_ATOMIC);
3956 type->atomic.akind = atomic_type;
3959 } else if (type_specifiers != 0) {
3960 errorf(HERE, "multiple datatypes in declaration");
3963 /* FIXME: check type qualifiers here */
3965 type->base.qualifiers = qualifiers;
3966 type->base.modifiers = modifiers;
3968 type_t *result = typehash_insert(type);
3969 if (newtype && result != type) {
3973 specifiers->type = result;
3977 specifiers->type = type_error_type;
3981 static type_qualifiers_t parse_type_qualifiers(void)
3983 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3986 switch (token.type) {
3987 /* type qualifiers */
3988 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3989 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3990 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3991 /* microsoft extended type modifiers */
3992 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3993 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3994 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3995 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3996 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
4005 * Parses an K&R identifier list
4007 static void parse_identifier_list(scope_t *scope)
4010 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
4011 entity->base.source_position = token.source_position;
4012 entity->base.namespc = NAMESPACE_NORMAL;
4013 entity->base.symbol = token.v.symbol;
4014 /* a K&R parameter has no type, yet */
4017 append_entity(scope, entity);
4019 if (token.type != ',') {
4023 } while (token.type == T_IDENTIFIER);
4026 static void semantic_parameter(declaration_t *declaration)
4028 /* TODO: improve error messages */
4029 source_position_t const* const pos = &declaration->base.source_position;
4031 /* §6.9.1:6 The declarations in the declaration list shall contain no
4032 * storage-class specifier other than register and no
4033 * initializations. */
4034 switch (declaration->declared_storage_class) {
4035 /* Allowed storage classes */
4036 case STORAGE_CLASS_NONE:
4037 case STORAGE_CLASS_REGISTER:
4041 errorf(pos, "parameter may only have none or register storage class");
4045 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type list in
4046 * a function declarator that is part of a definition of that
4047 * function shall not have incomplete type. */
4048 type_t *type = declaration->type;
4049 if (is_type_incomplete(skip_typeref(type))) {
4050 errorf(pos, "parameter '%#T' has incomplete type",
4051 type, declaration->base.symbol);
4055 static entity_t *parse_parameter(void)
4057 declaration_specifiers_t specifiers;
4058 memset(&specifiers, 0, sizeof(specifiers));
4060 parse_declaration_specifiers(&specifiers);
4062 entity_t *entity = parse_declarator(&specifiers,
4063 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
4064 anonymous_entity = NULL;
4069 * Parses function type parameters (and optionally creates variable_t entities
4070 * for them in a scope)
4072 static void parse_parameters(function_type_t *type, scope_t *scope)
4075 add_anchor_token(')');
4076 int saved_comma_state = save_and_reset_anchor_state(',');
4078 if (token.type == T_IDENTIFIER &&
4079 !is_typedef_symbol(token.v.symbol)) {
4080 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4081 if (la1_type == ',' || la1_type == ')') {
4082 type->kr_style_parameters = true;
4083 parse_identifier_list(scope);
4084 goto parameters_finished;
4088 if (token.type == ')') {
4089 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4090 if (!(c_mode & _CXX))
4091 type->unspecified_parameters = true;
4092 goto parameters_finished;
4095 function_parameter_t *parameter;
4096 function_parameter_t *last_parameter = NULL;
4099 switch (token.type) {
4102 type->variadic = true;
4103 goto parameters_finished;
4106 case T___extension__:
4109 entity_t *entity = parse_parameter();
4110 if (entity->kind == ENTITY_TYPEDEF) {
4111 errorf(&entity->base.source_position,
4112 "typedef not allowed as function parameter");
4115 assert(is_declaration(entity));
4117 /* func(void) is not a parameter */
4118 if (last_parameter == NULL
4119 && token.type == ')'
4120 && entity->base.symbol == NULL
4121 && skip_typeref(entity->declaration.type) == type_void) {
4122 goto parameters_finished;
4124 semantic_parameter(&entity->declaration);
4126 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4127 memset(parameter, 0, sizeof(parameter[0]));
4128 parameter->type = entity->declaration.type;
4130 if (scope != NULL) {
4131 append_entity(scope, entity);
4134 if (last_parameter != NULL) {
4135 last_parameter->next = parameter;
4137 type->parameters = parameter;
4139 last_parameter = parameter;
4144 goto parameters_finished;
4146 if (token.type != ',') {
4147 goto parameters_finished;
4153 parameters_finished:
4154 rem_anchor_token(')');
4158 restore_anchor_state(',', saved_comma_state);
4161 typedef enum construct_type_kind_t {
4164 CONSTRUCT_REFERENCE,
4167 } construct_type_kind_t;
4169 typedef struct construct_type_t construct_type_t;
4170 struct construct_type_t {
4171 construct_type_kind_t kind;
4172 construct_type_t *next;
4175 typedef struct parsed_pointer_t parsed_pointer_t;
4176 struct parsed_pointer_t {
4177 construct_type_t construct_type;
4178 type_qualifiers_t type_qualifiers;
4179 variable_t *base_variable; /**< MS __based extension. */
4182 typedef struct parsed_reference_t parsed_reference_t;
4183 struct parsed_reference_t {
4184 construct_type_t construct_type;
4187 typedef struct construct_function_type_t construct_function_type_t;
4188 struct construct_function_type_t {
4189 construct_type_t construct_type;
4190 type_t *function_type;
4193 typedef struct parsed_array_t parsed_array_t;
4194 struct parsed_array_t {
4195 construct_type_t construct_type;
4196 type_qualifiers_t type_qualifiers;
4202 typedef struct construct_base_type_t construct_base_type_t;
4203 struct construct_base_type_t {
4204 construct_type_t construct_type;
4208 static construct_type_t *parse_pointer_declarator(variable_t *base_variable)
4212 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4213 memset(pointer, 0, sizeof(pointer[0]));
4214 pointer->construct_type.kind = CONSTRUCT_POINTER;
4215 pointer->type_qualifiers = parse_type_qualifiers();
4216 pointer->base_variable = base_variable;
4218 return &pointer->construct_type;
4221 static construct_type_t *parse_reference_declarator(void)
4225 parsed_reference_t *reference = obstack_alloc(&temp_obst, sizeof(reference[0]));
4226 memset(reference, 0, sizeof(reference[0]));
4227 reference->construct_type.kind = CONSTRUCT_REFERENCE;
4229 return (construct_type_t*)reference;
4232 static construct_type_t *parse_array_declarator(void)
4235 add_anchor_token(']');
4237 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4238 memset(array, 0, sizeof(array[0]));
4239 array->construct_type.kind = CONSTRUCT_ARRAY;
4241 if (token.type == T_static) {
4242 array->is_static = true;
4246 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4247 if (type_qualifiers != 0) {
4248 if (token.type == T_static) {
4249 array->is_static = true;
4253 array->type_qualifiers = type_qualifiers;
4255 if (token.type == '*' && look_ahead(1)->type == ']') {
4256 array->is_variable = true;
4258 } else if (token.type != ']') {
4259 array->size = parse_assignment_expression();
4262 rem_anchor_token(']');
4266 return &array->construct_type;
4269 static construct_type_t *parse_function_declarator(scope_t *scope,
4270 decl_modifiers_t modifiers)
4272 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4273 function_type_t *ftype = &type->function;
4275 ftype->linkage = current_linkage;
4277 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
4278 case DM_NONE: break;
4279 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
4280 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
4281 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
4282 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
4285 errorf(HERE, "multiple calling conventions in declaration");
4289 parse_parameters(ftype, scope);
4291 construct_function_type_t *construct_function_type =
4292 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4293 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4294 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4295 construct_function_type->function_type = type;
4297 return &construct_function_type->construct_type;
4300 typedef struct parse_declarator_env_t {
4301 decl_modifiers_t modifiers;
4303 source_position_t source_position;
4305 } parse_declarator_env_t;
4307 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4308 bool may_be_abstract)
4310 /* construct a single linked list of construct_type_t's which describe
4311 * how to construct the final declarator type */
4312 construct_type_t *first = NULL;
4313 construct_type_t *last = NULL;
4314 gnu_attribute_t *attributes = NULL;
4316 decl_modifiers_t modifiers = parse_attributes(&attributes);
4318 /* MS __based extension */
4319 based_spec_t base_spec;
4320 base_spec.base_variable = NULL;
4323 construct_type_t *type;
4324 switch (token.type) {
4326 if (!(c_mode & _CXX))
4327 errorf(HERE, "references are only available for C++");
4328 if (base_spec.base_variable != NULL && warning.other) {
4329 warningf(&base_spec.source_position,
4330 "__based does not precede a pointer operator, ignored");
4332 type = parse_reference_declarator();
4334 base_spec.base_variable = NULL;
4338 type = parse_pointer_declarator(base_spec.base_variable);
4340 base_spec.base_variable = NULL;
4346 add_anchor_token(')');
4347 parse_microsoft_based(&base_spec);
4348 rem_anchor_token(')');
4353 goto ptr_operator_end;
4364 /* TODO: find out if this is correct */
4365 modifiers |= parse_attributes(&attributes);
4368 if (base_spec.base_variable != NULL && warning.other) {
4369 warningf(&base_spec.source_position,
4370 "__based does not precede a pointer operator, ignored");
4374 modifiers |= env->modifiers;
4375 env->modifiers = modifiers;
4378 construct_type_t *inner_types = NULL;
4380 switch (token.type) {
4383 errorf(HERE, "no identifier expected in typename");
4385 env->symbol = token.v.symbol;
4386 env->source_position = token.source_position;
4392 add_anchor_token(')');
4393 inner_types = parse_inner_declarator(env, may_be_abstract);
4394 if (inner_types != NULL) {
4395 /* All later declarators only modify the return type */
4398 rem_anchor_token(')');
4402 if (may_be_abstract)
4404 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4409 construct_type_t *p = last;
4412 construct_type_t *type;
4413 switch (token.type) {
4415 scope_t *scope = NULL;
4417 scope = &env->parameters;
4419 type = parse_function_declarator(scope, modifiers);
4423 type = parse_array_declarator();
4426 goto declarator_finished;
4429 /* insert in the middle of the list (behind p) */
4431 type->next = p->next;
4442 declarator_finished:
4443 /* append inner_types at the end of the list, we don't to set last anymore
4444 * as it's not needed anymore */
4446 assert(first == NULL);
4447 first = inner_types;
4449 last->next = inner_types;
4457 static void parse_declaration_attributes(entity_t *entity)
4459 gnu_attribute_t *attributes = NULL;
4460 decl_modifiers_t modifiers = parse_attributes(&attributes);
4466 if (entity->kind == ENTITY_TYPEDEF) {
4467 modifiers |= entity->typedefe.modifiers;
4468 type = entity->typedefe.type;
4470 assert(is_declaration(entity));
4471 modifiers |= entity->declaration.modifiers;
4472 type = entity->declaration.type;
4477 /* handle these strange/stupid mode attributes */
4478 gnu_attribute_t *attribute = attributes;
4479 for ( ; attribute != NULL; attribute = attribute->next) {
4480 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4483 atomic_type_kind_t akind = attribute->u.akind;
4484 if (!is_type_signed(type)) {
4486 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4487 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4488 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4489 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4491 panic("invalid akind in mode attribute");
4495 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4496 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4497 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4498 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4500 panic("invalid akind in mode attribute");
4504 type = make_atomic_type(akind, type->base.qualifiers);
4507 type_modifiers_t type_modifiers = type->base.modifiers;
4508 if (modifiers & DM_TRANSPARENT_UNION)
4509 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4511 if (type->base.modifiers != type_modifiers) {
4512 type_t *copy = duplicate_type(type);
4513 copy->base.modifiers = type_modifiers;
4515 type = typehash_insert(copy);
4517 obstack_free(type_obst, copy);
4521 if (entity->kind == ENTITY_TYPEDEF) {
4522 entity->typedefe.type = type;
4523 entity->typedefe.modifiers = modifiers;
4525 entity->declaration.type = type;
4526 entity->declaration.modifiers = modifiers;
4530 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
4532 construct_type_t *iter = construct_list;
4533 for (; iter != NULL; iter = iter->next) {
4534 switch (iter->kind) {
4535 case CONSTRUCT_INVALID:
4536 internal_errorf(HERE, "invalid type construction found");
4537 case CONSTRUCT_FUNCTION: {
4538 construct_function_type_t *construct_function_type
4539 = (construct_function_type_t*) iter;
4541 type_t *function_type = construct_function_type->function_type;
4543 function_type->function.return_type = type;
4545 type_t *skipped_return_type = skip_typeref(type);
4547 if (is_type_function(skipped_return_type)) {
4548 errorf(HERE, "function returning function is not allowed");
4549 } else if (is_type_array(skipped_return_type)) {
4550 errorf(HERE, "function returning array is not allowed");
4552 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4554 "type qualifiers in return type of function type are meaningless");
4558 type = function_type;
4562 case CONSTRUCT_POINTER: {
4563 if (is_type_reference(skip_typeref(type)))
4564 errorf(HERE, "cannot declare a pointer to reference");
4566 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4567 type = make_based_pointer_type(type, parsed_pointer->type_qualifiers, parsed_pointer->base_variable);
4571 case CONSTRUCT_REFERENCE:
4572 if (is_type_reference(skip_typeref(type)))
4573 errorf(HERE, "cannot declare a reference to reference");
4575 type = make_reference_type(type);
4578 case CONSTRUCT_ARRAY: {
4579 if (is_type_reference(skip_typeref(type)))
4580 errorf(HERE, "cannot declare an array of references");
4582 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4583 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4585 expression_t *size_expression = parsed_array->size;
4586 if (size_expression != NULL) {
4588 = create_implicit_cast(size_expression, type_size_t);
4591 array_type->base.qualifiers = parsed_array->type_qualifiers;
4592 array_type->array.element_type = type;
4593 array_type->array.is_static = parsed_array->is_static;
4594 array_type->array.is_variable = parsed_array->is_variable;
4595 array_type->array.size_expression = size_expression;
4597 if (size_expression != NULL) {
4598 if (is_constant_expression(size_expression)) {
4599 array_type->array.size_constant = true;
4600 array_type->array.size
4601 = fold_constant(size_expression);
4603 array_type->array.is_vla = true;
4607 type_t *skipped_type = skip_typeref(type);
4609 if (is_type_incomplete(skipped_type)) {
4610 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4611 } else if (is_type_function(skipped_type)) {
4612 errorf(HERE, "array of functions is not allowed");
4619 type_t *hashed_type = typehash_insert(type);
4620 if (hashed_type != type) {
4621 /* the function type was constructed earlier freeing it here will
4622 * destroy other types... */
4623 if (iter->kind != CONSTRUCT_FUNCTION) {
4633 static type_t *automatic_type_conversion(type_t *orig_type);
4635 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4636 declarator_flags_t flags)
4638 parse_declarator_env_t env;
4639 memset(&env, 0, sizeof(env));
4640 env.modifiers = specifiers->modifiers;
4642 construct_type_t *construct_type =
4643 parse_inner_declarator(&env, (flags & DECL_MAY_BE_ABSTRACT) != 0);
4645 construct_declarator_type(construct_type, specifiers->type);
4646 type_t *type = skip_typeref(orig_type);
4648 if (construct_type != NULL) {
4649 obstack_free(&temp_obst, construct_type);
4653 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4654 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4655 entity->base.symbol = env.symbol;
4656 entity->base.source_position = env.source_position;
4657 entity->typedefe.type = orig_type;
4659 if (anonymous_entity != NULL) {
4660 if (is_type_compound(type)) {
4661 assert(anonymous_entity->compound.alias == NULL);
4662 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4663 anonymous_entity->kind == ENTITY_UNION);
4664 anonymous_entity->compound.alias = entity;
4665 anonymous_entity = NULL;
4666 } else if (is_type_enum(type)) {
4667 assert(anonymous_entity->enume.alias == NULL);
4668 assert(anonymous_entity->kind == ENTITY_ENUM);
4669 anonymous_entity->enume.alias = entity;
4670 anonymous_entity = NULL;
4674 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4675 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4676 } else if (flags & DECL_IS_PARAMETER) {
4677 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4678 * shall be adjusted to ``qualified pointer to type'',
4680 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4681 * type'' shall be adjusted to ``pointer to function
4682 * returning type'', as in 6.3.2.1. */
4683 orig_type = automatic_type_conversion(type);
4684 goto create_variable;
4685 } else if (is_type_function(type)) {
4686 entity = allocate_entity_zero(ENTITY_FUNCTION);
4688 entity->function.is_inline = specifiers->is_inline;
4689 entity->function.parameters = env.parameters;
4692 entity = allocate_entity_zero(ENTITY_VARIABLE);
4694 entity->variable.get_property_sym = specifiers->get_property_sym;
4695 entity->variable.put_property_sym = specifiers->put_property_sym;
4696 if (specifiers->alignment != 0) {
4697 /* TODO: add checks here */
4698 entity->variable.alignment = specifiers->alignment;
4701 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4702 warningf(&env.source_position,
4703 "variable '%Y' declared 'inline'\n", env.symbol);
4707 entity->base.source_position = env.source_position;
4708 entity->base.symbol = env.symbol;
4709 entity->base.namespc = NAMESPACE_NORMAL;
4710 entity->declaration.type = orig_type;
4711 entity->declaration.modifiers = env.modifiers;
4712 entity->declaration.deprecated_string = specifiers->deprecated_string;
4714 storage_class_t storage_class = specifiers->storage_class;
4715 entity->declaration.declared_storage_class = storage_class;
4717 if (storage_class == STORAGE_CLASS_NONE
4718 && current_scope != file_scope) {
4719 storage_class = STORAGE_CLASS_AUTO;
4721 entity->declaration.storage_class = storage_class;
4724 parse_declaration_attributes(entity);
4729 static type_t *parse_abstract_declarator(type_t *base_type)
4731 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4733 type_t *result = construct_declarator_type(construct_type, base_type);
4734 if (construct_type != NULL) {
4735 obstack_free(&temp_obst, construct_type);
4742 * Check if the declaration of main is suspicious. main should be a
4743 * function with external linkage, returning int, taking either zero
4744 * arguments, two, or three arguments of appropriate types, ie.
4746 * int main([ int argc, char **argv [, char **env ] ]).
4748 * @param decl the declaration to check
4749 * @param type the function type of the declaration
4751 static void check_type_of_main(const entity_t *entity)
4753 const source_position_t *pos = &entity->base.source_position;
4754 if (entity->kind != ENTITY_FUNCTION) {
4755 warningf(pos, "'main' is not a function");
4759 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4760 warningf(pos, "'main' is normally a non-static function");
4763 type_t *type = skip_typeref(entity->declaration.type);
4764 assert(is_type_function(type));
4766 function_type_t *func_type = &type->function;
4767 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4768 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4769 func_type->return_type);
4771 const function_parameter_t *parm = func_type->parameters;
4773 type_t *const first_type = parm->type;
4774 if (!types_compatible(skip_typeref(first_type), type_int)) {
4776 "first argument of 'main' should be 'int', but is '%T'",
4781 type_t *const second_type = parm->type;
4782 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4783 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4787 type_t *const third_type = parm->type;
4788 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4789 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4793 goto warn_arg_count;
4797 warningf(pos, "'main' takes only zero, two or three arguments");
4803 * Check if a symbol is the equal to "main".
4805 static bool is_sym_main(const symbol_t *const sym)
4807 return strcmp(sym->string, "main") == 0;
4810 static const char *get_entity_kind_name(entity_kind_t kind)
4812 switch ((entity_kind_tag_t) kind) {
4813 case ENTITY_FUNCTION: return "function";
4814 case ENTITY_VARIABLE: return "variable";
4815 case ENTITY_COMPOUND_MEMBER: return "compound type member";
4816 case ENTITY_STRUCT: return "struct";
4817 case ENTITY_UNION: return "union";
4818 case ENTITY_ENUM: return "enum";
4819 case ENTITY_ENUM_VALUE: return "enum value";
4820 case ENTITY_LABEL: return "label";
4821 case ENTITY_LOCAL_LABEL: return "local label";
4822 case ENTITY_TYPEDEF: return "typedef";
4823 case ENTITY_NAMESPACE: return "namespace";
4824 case ENTITY_INVALID: break;
4827 panic("Invalid entity kind encountered in get_entity_kind_name");
4830 static void error_redefined_as_different_kind(const source_position_t *pos,
4831 const entity_t *old, entity_kind_t new_kind)
4833 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4834 get_entity_kind_name(old->kind), old->base.symbol,
4835 get_entity_kind_name(new_kind), &old->base.source_position);
4839 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4840 * for various problems that occur for multiple definitions
4842 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4844 const symbol_t *const symbol = entity->base.symbol;
4845 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4846 const source_position_t *pos = &entity->base.source_position;
4848 assert(symbol != NULL);
4849 entity_t *previous_entity = get_entity(symbol, namespc);
4850 /* pushing the same entity twice will break the stack structure */
4851 assert(previous_entity != entity);
4853 if (entity->kind == ENTITY_FUNCTION) {
4854 type_t *const orig_type = entity->declaration.type;
4855 type_t *const type = skip_typeref(orig_type);
4857 assert(is_type_function(type));
4858 if (type->function.unspecified_parameters &&
4859 warning.strict_prototypes &&
4860 previous_entity == NULL) {
4861 warningf(pos, "function declaration '%#T' is not a prototype",
4865 if (warning.main && current_scope == file_scope
4866 && is_sym_main(symbol)) {
4867 check_type_of_main(entity);
4871 if (is_declaration(entity)) {
4872 if (warning.nested_externs
4873 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4874 && current_scope != file_scope) {
4875 warningf(pos, "nested extern declaration of '%#T'",
4876 entity->declaration.type, symbol);
4880 if (previous_entity != NULL
4881 && previous_entity->base.parent_scope == ¤t_function->parameters
4882 && current_scope->depth == previous_entity->base.parent_scope->depth+1){
4884 assert(previous_entity->kind == ENTITY_VARIABLE);
4886 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4887 entity->declaration.type, symbol,
4888 previous_entity->declaration.type, symbol,
4889 &previous_entity->base.source_position);
4893 if (previous_entity != NULL
4894 && previous_entity->base.parent_scope == current_scope) {
4896 if (previous_entity->kind != entity->kind) {
4897 error_redefined_as_different_kind(pos, previous_entity,
4901 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4903 "redeclaration of enum entry '%Y' (declared %P)",
4904 symbol, &previous_entity->base.source_position);
4907 if (previous_entity->kind == ENTITY_TYPEDEF) {
4908 /* TODO: C++ allows this for exactly the same type */
4910 "redefinition of typedef '%Y' (declared %P)",
4911 symbol, &previous_entity->base.source_position);
4915 /* at this point we should have only VARIABLES or FUNCTIONS */
4916 assert(is_declaration(previous_entity) && is_declaration(entity));
4918 /* can happen for K&R style declarations */
4919 if (previous_entity->kind == ENTITY_VARIABLE
4920 && previous_entity->declaration.type == NULL
4921 && entity->kind == ENTITY_VARIABLE) {
4922 previous_entity->declaration.type = entity->declaration.type;
4923 previous_entity->declaration.storage_class
4924 = entity->declaration.storage_class;
4925 previous_entity->declaration.declared_storage_class
4926 = entity->declaration.declared_storage_class;
4927 previous_entity->declaration.modifiers
4928 = entity->declaration.modifiers;
4929 previous_entity->declaration.deprecated_string
4930 = entity->declaration.deprecated_string;
4932 assert(entity->declaration.type != NULL);
4934 declaration_t *const previous_declaration
4935 = &previous_entity->declaration;
4936 declaration_t *const declaration = &entity->declaration;
4937 type_t *const orig_type = entity->declaration.type;
4938 type_t *const type = skip_typeref(orig_type);
4940 type_t *prev_type = skip_typeref(previous_declaration->type);
4942 if (!types_compatible(type, prev_type)) {
4944 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4945 orig_type, symbol, previous_declaration->type, symbol,
4946 &previous_entity->base.source_position);
4948 unsigned old_storage_class = previous_declaration->storage_class;
4949 if (warning.redundant_decls && is_definition
4950 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4951 && !(previous_declaration->modifiers & DM_USED)
4952 && !previous_declaration->used) {
4953 warningf(&previous_entity->base.source_position,
4954 "unnecessary static forward declaration for '%#T'",
4955 previous_declaration->type, symbol);
4958 unsigned new_storage_class = declaration->storage_class;
4959 if (is_type_incomplete(prev_type)) {
4960 previous_declaration->type = type;
4964 /* pretend no storage class means extern for function
4965 * declarations (except if the previous declaration is neither
4966 * none nor extern) */
4967 if (entity->kind == ENTITY_FUNCTION) {
4968 if (prev_type->function.unspecified_parameters) {
4969 previous_declaration->type = type;
4973 switch (old_storage_class) {
4974 case STORAGE_CLASS_NONE:
4975 old_storage_class = STORAGE_CLASS_EXTERN;
4978 case STORAGE_CLASS_EXTERN:
4979 if (is_definition) {
4980 if (warning.missing_prototypes &&
4981 prev_type->function.unspecified_parameters &&
4982 !is_sym_main(symbol)) {
4983 warningf(pos, "no previous prototype for '%#T'",
4986 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4987 new_storage_class = STORAGE_CLASS_EXTERN;
4996 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4997 new_storage_class == STORAGE_CLASS_EXTERN) {
4998 warn_redundant_declaration:
4999 if (!is_definition &&
5000 warning.redundant_decls &&
5001 is_type_valid(prev_type) &&
5002 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
5004 "redundant declaration for '%Y' (declared %P)",
5005 symbol, &previous_entity->base.source_position);
5007 } else if (current_function == NULL) {
5008 if (old_storage_class != STORAGE_CLASS_STATIC &&
5009 new_storage_class == STORAGE_CLASS_STATIC) {
5011 "static declaration of '%Y' follows non-static declaration (declared %P)",
5012 symbol, &previous_entity->base.source_position);
5013 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
5014 previous_declaration->storage_class = STORAGE_CLASS_NONE;
5015 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
5017 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
5019 goto error_redeclaration;
5020 goto warn_redundant_declaration;
5022 } else if (is_type_valid(prev_type)) {
5023 if (old_storage_class == new_storage_class) {
5024 error_redeclaration:
5025 errorf(pos, "redeclaration of '%Y' (declared %P)",
5026 symbol, &previous_entity->base.source_position);
5029 "redeclaration of '%Y' with different linkage (declared %P)",
5030 symbol, &previous_entity->base.source_position);
5035 previous_declaration->modifiers |= declaration->modifiers;
5036 if (entity->kind == ENTITY_FUNCTION) {
5037 previous_entity->function.is_inline |= entity->function.is_inline;
5039 return previous_entity;
5042 if (entity->kind == ENTITY_FUNCTION) {
5043 if (is_definition &&
5044 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
5045 if (warning.missing_prototypes && !is_sym_main(symbol)) {
5046 warningf(pos, "no previous prototype for '%#T'",
5047 entity->declaration.type, symbol);
5048 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
5049 warningf(pos, "no previous declaration for '%#T'",
5050 entity->declaration.type, symbol);
5053 } else if (warning.missing_declarations
5054 && entity->kind == ENTITY_VARIABLE
5055 && current_scope == file_scope) {
5056 declaration_t *declaration = &entity->declaration;
5057 if (declaration->storage_class == STORAGE_CLASS_NONE ||
5058 declaration->storage_class == STORAGE_CLASS_THREAD) {
5059 warningf(pos, "no previous declaration for '%#T'",
5060 declaration->type, symbol);
5065 assert(entity->base.parent_scope == NULL);
5066 assert(current_scope != NULL);
5068 entity->base.parent_scope = current_scope;
5069 entity->base.namespc = NAMESPACE_NORMAL;
5070 environment_push(entity);
5071 append_entity(current_scope, entity);
5076 static void parser_error_multiple_definition(entity_t *entity,
5077 const source_position_t *source_position)
5079 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
5080 entity->base.symbol, &entity->base.source_position);
5083 static bool is_declaration_specifier(const token_t *token,
5084 bool only_specifiers_qualifiers)
5086 switch (token->type) {
5091 return is_typedef_symbol(token->v.symbol);
5093 case T___extension__:
5095 return !only_specifiers_qualifiers;
5102 static void parse_init_declarator_rest(entity_t *entity)
5104 assert(is_declaration(entity));
5105 declaration_t *const declaration = &entity->declaration;
5109 type_t *orig_type = declaration->type;
5110 type_t *type = skip_typeref(orig_type);
5112 if (entity->kind == ENTITY_VARIABLE
5113 && entity->variable.initializer != NULL) {
5114 parser_error_multiple_definition(entity, HERE);
5117 bool must_be_constant = false;
5118 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
5119 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
5120 entity->base.parent_scope == file_scope) {
5121 must_be_constant = true;
5124 if (is_type_function(type)) {
5125 errorf(&entity->base.source_position,
5126 "function '%#T' is initialized like a variable",
5127 orig_type, entity->base.symbol);
5128 orig_type = type_error_type;
5131 parse_initializer_env_t env;
5132 env.type = orig_type;
5133 env.must_be_constant = must_be_constant;
5134 env.entity = entity;
5135 current_init_decl = entity;
5137 initializer_t *initializer = parse_initializer(&env);
5138 current_init_decl = NULL;
5140 if (entity->kind == ENTITY_VARIABLE) {
5141 /* § 6.7.5 (22) array initializers for arrays with unknown size
5142 * determine the array type size */
5143 declaration->type = env.type;
5144 entity->variable.initializer = initializer;
5148 /* parse rest of a declaration without any declarator */
5149 static void parse_anonymous_declaration_rest(
5150 const declaration_specifiers_t *specifiers)
5153 anonymous_entity = NULL;
5155 if (warning.other) {
5156 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5157 warningf(&specifiers->source_position,
5158 "useless storage class in empty declaration");
5161 type_t *type = specifiers->type;
5162 switch (type->kind) {
5163 case TYPE_COMPOUND_STRUCT:
5164 case TYPE_COMPOUND_UNION: {
5165 if (type->compound.compound->base.symbol == NULL) {
5166 warningf(&specifiers->source_position,
5167 "unnamed struct/union that defines no instances");
5176 warningf(&specifiers->source_position, "empty declaration");
5182 static void check_variable_type_complete(entity_t *ent)
5184 if (ent->kind != ENTITY_VARIABLE)
5187 /* §6.7:7 If an identifier for an object is declared with no linkage, the
5188 * type for the object shall be complete [...] */
5189 declaration_t *decl = &ent->declaration;
5190 if (decl->storage_class != STORAGE_CLASS_NONE)
5193 type_t *type = decl->type;
5194 if (!is_type_incomplete(skip_typeref(type)))
5197 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
5198 type, ent->base.symbol);
5202 static void parse_declaration_rest(entity_t *ndeclaration,
5203 const declaration_specifiers_t *specifiers,
5204 parsed_declaration_func finished_declaration)
5206 add_anchor_token(';');
5207 add_anchor_token(',');
5209 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5211 if (token.type == '=') {
5212 parse_init_declarator_rest(entity);
5213 } else if (entity->kind == ENTITY_VARIABLE) {
5214 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
5215 * [...] where the extern specifier is explicitly used. */
5216 declaration_t *decl = &entity->declaration;
5217 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
5218 type_t *type = decl->type;
5219 if (is_type_reference(skip_typeref(type))) {
5220 errorf(&entity->base.source_position,
5221 "reference '%#T' must be initialized",
5222 type, entity->base.symbol);
5227 check_variable_type_complete(entity);
5229 if (token.type != ',')
5233 add_anchor_token('=');
5234 ndeclaration = parse_declarator(specifiers, DECL_FLAGS_NONE);
5235 rem_anchor_token('=');
5240 anonymous_entity = NULL;
5241 rem_anchor_token(';');
5242 rem_anchor_token(',');
5245 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5247 symbol_t *symbol = entity->base.symbol;
5248 if (symbol == NULL) {
5249 errorf(HERE, "anonymous declaration not valid as function parameter");
5253 assert(entity->base.namespc == NAMESPACE_NORMAL);
5254 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5255 if (previous_entity == NULL
5256 || previous_entity->base.parent_scope != current_scope) {
5257 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5262 if (is_definition) {
5263 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5266 return record_entity(entity, false);
5269 static void parse_declaration(parsed_declaration_func finished_declaration)
5271 declaration_specifiers_t specifiers;
5272 memset(&specifiers, 0, sizeof(specifiers));
5274 add_anchor_token(';');
5275 parse_declaration_specifiers(&specifiers);
5276 rem_anchor_token(';');
5278 if (token.type == ';') {
5279 parse_anonymous_declaration_rest(&specifiers);
5281 entity_t *entity = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5282 parse_declaration_rest(entity, &specifiers, finished_declaration);
5286 static type_t *get_default_promoted_type(type_t *orig_type)
5288 type_t *result = orig_type;
5290 type_t *type = skip_typeref(orig_type);
5291 if (is_type_integer(type)) {
5292 result = promote_integer(type);
5293 } else if (type == type_float) {
5294 result = type_double;
5300 static void parse_kr_declaration_list(entity_t *entity)
5302 if (entity->kind != ENTITY_FUNCTION)
5305 type_t *type = skip_typeref(entity->declaration.type);
5306 assert(is_type_function(type));
5307 if (!type->function.kr_style_parameters)
5311 add_anchor_token('{');
5313 /* push function parameters */
5314 size_t const top = environment_top();
5315 scope_push(&entity->function.parameters);
5317 entity_t *parameter = entity->function.parameters.entities;
5318 for ( ; parameter != NULL; parameter = parameter->base.next) {
5319 assert(parameter->base.parent_scope == NULL);
5320 parameter->base.parent_scope = current_scope;
5321 environment_push(parameter);
5324 /* parse declaration list */
5325 while (is_declaration_specifier(&token, false)) {
5326 parse_declaration(finished_kr_declaration);
5329 /* pop function parameters */
5330 assert(current_scope == &entity->function.parameters);
5332 environment_pop_to(top);
5334 /* update function type */
5335 type_t *new_type = duplicate_type(type);
5337 function_parameter_t *parameters = NULL;
5338 function_parameter_t *last_parameter = NULL;
5340 entity_t *parameter_declaration = entity->function.parameters.entities;
5341 for (; parameter_declaration != NULL;
5342 parameter_declaration = parameter_declaration->base.next) {
5343 type_t *parameter_type = parameter_declaration->declaration.type;
5344 if (parameter_type == NULL) {
5346 errorf(HERE, "no type specified for function parameter '%Y'",
5347 parameter_declaration->base.symbol);
5349 if (warning.implicit_int) {
5350 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5351 parameter_declaration->base.symbol);
5353 parameter_type = type_int;
5354 parameter_declaration->declaration.type = parameter_type;
5358 semantic_parameter(¶meter_declaration->declaration);
5359 parameter_type = parameter_declaration->declaration.type;
5362 * we need the default promoted types for the function type
5364 parameter_type = get_default_promoted_type(parameter_type);
5366 function_parameter_t *function_parameter
5367 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5368 memset(function_parameter, 0, sizeof(function_parameter[0]));
5370 function_parameter->type = parameter_type;
5371 if (last_parameter != NULL) {
5372 last_parameter->next = function_parameter;
5374 parameters = function_parameter;
5376 last_parameter = function_parameter;
5379 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5381 new_type->function.parameters = parameters;
5382 new_type->function.unspecified_parameters = true;
5384 type = typehash_insert(new_type);
5385 if (type != new_type) {
5386 obstack_free(type_obst, new_type);
5389 entity->declaration.type = type;
5391 rem_anchor_token('{');
5394 static bool first_err = true;
5397 * When called with first_err set, prints the name of the current function,
5400 static void print_in_function(void)
5404 diagnosticf("%s: In function '%Y':\n",
5405 current_function->base.base.source_position.input_name,
5406 current_function->base.base.symbol);
5411 * Check if all labels are defined in the current function.
5412 * Check if all labels are used in the current function.
5414 static void check_labels(void)
5416 for (const goto_statement_t *goto_statement = goto_first;
5417 goto_statement != NULL;
5418 goto_statement = goto_statement->next) {
5419 /* skip computed gotos */
5420 if (goto_statement->expression != NULL)
5423 label_t *label = goto_statement->label;
5426 if (label->base.source_position.input_name == NULL) {
5427 print_in_function();
5428 errorf(&goto_statement->base.source_position,
5429 "label '%Y' used but not defined", label->base.symbol);
5433 if (warning.unused_label) {
5434 for (const label_statement_t *label_statement = label_first;
5435 label_statement != NULL;
5436 label_statement = label_statement->next) {
5437 label_t *label = label_statement->label;
5439 if (! label->used) {
5440 print_in_function();
5441 warningf(&label_statement->base.source_position,
5442 "label '%Y' defined but not used", label->base.symbol);
5448 static void warn_unused_decl(entity_t *entity, entity_t *end,
5449 char const *const what)
5451 for (; entity != NULL; entity = entity->base.next) {
5452 if (!is_declaration(entity))
5455 declaration_t *declaration = &entity->declaration;
5456 if (declaration->implicit)
5459 if (!declaration->used) {
5460 print_in_function();
5461 warningf(&entity->base.source_position, "%s '%Y' is unused",
5462 what, entity->base.symbol);
5463 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5464 print_in_function();
5465 warningf(&entity->base.source_position, "%s '%Y' is never read",
5466 what, entity->base.symbol);
5474 static void check_unused_variables(statement_t *const stmt, void *const env)
5478 switch (stmt->kind) {
5479 case STATEMENT_DECLARATION: {
5480 declaration_statement_t const *const decls = &stmt->declaration;
5481 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5487 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5496 * Check declarations of current_function for unused entities.
5498 static void check_declarations(void)
5500 if (warning.unused_parameter) {
5501 const scope_t *scope = ¤t_function->parameters;
5503 /* do not issue unused warnings for main */
5504 if (!is_sym_main(current_function->base.base.symbol)) {
5505 warn_unused_decl(scope->entities, NULL, "parameter");
5508 if (warning.unused_variable) {
5509 walk_statements(current_function->statement, check_unused_variables,
5514 static int determine_truth(expression_t const* const cond)
5517 !is_constant_expression(cond) ? 0 :
5518 fold_constant(cond) != 0 ? 1 :
5522 static bool expression_returns(expression_t const *const expr)
5524 switch (expr->kind) {
5526 expression_t const *const func = expr->call.function;
5527 if (func->kind == EXPR_REFERENCE) {
5528 entity_t *entity = func->reference.entity;
5529 if (entity->kind == ENTITY_FUNCTION
5530 && entity->declaration.modifiers & DM_NORETURN)
5534 if (!expression_returns(func))
5537 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5538 if (!expression_returns(arg->expression))
5545 case EXPR_REFERENCE:
5546 case EXPR_REFERENCE_ENUM_VALUE:
5548 case EXPR_CHARACTER_CONSTANT:
5549 case EXPR_WIDE_CHARACTER_CONSTANT:
5550 case EXPR_STRING_LITERAL:
5551 case EXPR_WIDE_STRING_LITERAL:
5552 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5553 case EXPR_LABEL_ADDRESS:
5554 case EXPR_CLASSIFY_TYPE:
5555 case EXPR_SIZEOF: // TODO handle obscure VLA case
5558 case EXPR_BUILTIN_SYMBOL:
5559 case EXPR_BUILTIN_CONSTANT_P:
5560 case EXPR_BUILTIN_PREFETCH:
5563 case EXPR_STATEMENT: // TODO implement
5566 case EXPR_CONDITIONAL:
5567 // TODO handle constant expression
5569 expression_returns(expr->conditional.condition) && (
5570 expression_returns(expr->conditional.true_expression) ||
5571 expression_returns(expr->conditional.false_expression)
5575 return expression_returns(expr->select.compound);
5577 case EXPR_ARRAY_ACCESS:
5579 expression_returns(expr->array_access.array_ref) &&
5580 expression_returns(expr->array_access.index);
5583 return expression_returns(expr->va_starte.ap);
5586 return expression_returns(expr->va_arge.ap);
5588 EXPR_UNARY_CASES_MANDATORY
5589 return expression_returns(expr->unary.value);
5591 case EXPR_UNARY_THROW:
5595 // TODO handle constant lhs of && and ||
5597 expression_returns(expr->binary.left) &&
5598 expression_returns(expr->binary.right);
5604 panic("unhandled expression");
5607 static bool noreturn_candidate;
5609 static void check_reachable(statement_t *const stmt)
5611 if (stmt->base.reachable)
5613 if (stmt->kind != STATEMENT_DO_WHILE)
5614 stmt->base.reachable = true;
5616 statement_t *last = stmt;
5618 switch (stmt->kind) {
5619 case STATEMENT_INVALID:
5620 case STATEMENT_EMPTY:
5621 case STATEMENT_DECLARATION:
5622 case STATEMENT_LOCAL_LABEL:
5624 next = stmt->base.next;
5627 case STATEMENT_COMPOUND:
5628 next = stmt->compound.statements;
5631 case STATEMENT_RETURN:
5632 noreturn_candidate = false;
5635 case STATEMENT_IF: {
5636 if_statement_t const* const ifs = &stmt->ifs;
5637 int const val = determine_truth(ifs->condition);
5640 check_reachable(ifs->true_statement);
5645 if (ifs->false_statement != NULL) {
5646 check_reachable(ifs->false_statement);
5650 next = stmt->base.next;
5654 case STATEMENT_SWITCH: {
5655 switch_statement_t const *const switchs = &stmt->switchs;
5656 expression_t const *const expr = switchs->expression;
5658 if (is_constant_expression(expr)) {
5659 long const val = fold_constant(expr);
5660 case_label_statement_t * defaults = NULL;
5661 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5662 if (i->expression == NULL) {
5667 if (i->first_case <= val && val <= i->last_case) {
5668 check_reachable((statement_t*)i);
5673 if (defaults != NULL) {
5674 check_reachable((statement_t*)defaults);
5678 bool has_default = false;
5679 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5680 if (i->expression == NULL)
5683 check_reachable((statement_t*)i);
5690 next = stmt->base.next;
5694 case STATEMENT_EXPRESSION: {
5695 /* Check for noreturn function call */
5696 expression_t const *const expr = stmt->expression.expression;
5697 if (!expression_returns(expr))
5700 next = stmt->base.next;
5704 case STATEMENT_CONTINUE: {
5705 statement_t *parent = stmt;
5707 parent = parent->base.parent;
5708 if (parent == NULL) /* continue not within loop */
5712 switch (parent->kind) {
5713 case STATEMENT_WHILE: goto continue_while;
5714 case STATEMENT_DO_WHILE: goto continue_do_while;
5715 case STATEMENT_FOR: goto continue_for;
5722 case STATEMENT_BREAK: {
5723 statement_t *parent = stmt;
5725 parent = parent->base.parent;
5726 if (parent == NULL) /* break not within loop/switch */
5729 switch (parent->kind) {
5730 case STATEMENT_SWITCH:
5731 case STATEMENT_WHILE:
5732 case STATEMENT_DO_WHILE:
5735 next = parent->base.next;
5736 goto found_break_parent;
5745 case STATEMENT_GOTO:
5746 if (stmt->gotos.expression) {
5747 statement_t *parent = stmt->base.parent;
5748 if (parent == NULL) /* top level goto */
5752 next = stmt->gotos.label->statement;
5753 if (next == NULL) /* missing label */
5758 case STATEMENT_LABEL:
5759 next = stmt->label.statement;
5762 case STATEMENT_CASE_LABEL:
5763 next = stmt->case_label.statement;
5766 case STATEMENT_WHILE: {
5767 while_statement_t const *const whiles = &stmt->whiles;
5768 int const val = determine_truth(whiles->condition);
5771 check_reachable(whiles->body);
5776 next = stmt->base.next;
5780 case STATEMENT_DO_WHILE:
5781 next = stmt->do_while.body;
5784 case STATEMENT_FOR: {
5785 for_statement_t *const fors = &stmt->fors;
5787 if (fors->condition_reachable)
5789 fors->condition_reachable = true;
5791 expression_t const *const cond = fors->condition;
5793 cond == NULL ? 1 : determine_truth(cond);
5796 check_reachable(fors->body);
5801 next = stmt->base.next;
5805 case STATEMENT_MS_TRY: {
5806 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5807 check_reachable(ms_try->try_statement);
5808 next = ms_try->final_statement;
5812 case STATEMENT_LEAVE: {
5813 statement_t *parent = stmt;
5815 parent = parent->base.parent;
5816 if (parent == NULL) /* __leave not within __try */
5819 if (parent->kind == STATEMENT_MS_TRY) {
5821 next = parent->ms_try.final_statement;
5829 while (next == NULL) {
5830 next = last->base.parent;
5832 noreturn_candidate = false;
5834 type_t *const type = current_function->base.type;
5835 assert(is_type_function(type));
5836 type_t *const ret = skip_typeref(type->function.return_type);
5837 if (warning.return_type &&
5838 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5839 is_type_valid(ret) &&
5840 !is_sym_main(current_function->base.base.symbol)) {
5841 warningf(&stmt->base.source_position,
5842 "control reaches end of non-void function");
5847 switch (next->kind) {
5848 case STATEMENT_INVALID:
5849 case STATEMENT_EMPTY:
5850 case STATEMENT_DECLARATION:
5851 case STATEMENT_LOCAL_LABEL:
5852 case STATEMENT_EXPRESSION:
5854 case STATEMENT_RETURN:
5855 case STATEMENT_CONTINUE:
5856 case STATEMENT_BREAK:
5857 case STATEMENT_GOTO:
5858 case STATEMENT_LEAVE:
5859 panic("invalid control flow in function");
5861 case STATEMENT_COMPOUND:
5863 case STATEMENT_SWITCH:
5864 case STATEMENT_LABEL:
5865 case STATEMENT_CASE_LABEL:
5867 next = next->base.next;
5870 case STATEMENT_WHILE: {
5872 if (next->base.reachable)
5874 next->base.reachable = true;
5876 while_statement_t const *const whiles = &next->whiles;
5877 int const val = determine_truth(whiles->condition);
5880 check_reachable(whiles->body);
5886 next = next->base.next;
5890 case STATEMENT_DO_WHILE: {
5892 if (next->base.reachable)
5894 next->base.reachable = true;
5896 do_while_statement_t const *const dw = &next->do_while;
5897 int const val = determine_truth(dw->condition);
5900 check_reachable(dw->body);
5906 next = next->base.next;
5910 case STATEMENT_FOR: {
5912 for_statement_t *const fors = &next->fors;
5914 fors->step_reachable = true;
5916 if (fors->condition_reachable)
5918 fors->condition_reachable = true;
5920 expression_t const *const cond = fors->condition;
5922 cond == NULL ? 1 : determine_truth(cond);
5925 check_reachable(fors->body);
5931 next = next->base.next;
5935 case STATEMENT_MS_TRY:
5937 next = next->ms_try.final_statement;
5942 check_reachable(next);
5945 static void check_unreachable(statement_t* const stmt, void *const env)
5949 switch (stmt->kind) {
5950 case STATEMENT_DO_WHILE:
5951 if (!stmt->base.reachable) {
5952 expression_t const *const cond = stmt->do_while.condition;
5953 if (determine_truth(cond) >= 0) {
5954 warningf(&cond->base.source_position,
5955 "condition of do-while-loop is unreachable");
5960 case STATEMENT_FOR: {
5961 for_statement_t const* const fors = &stmt->fors;
5963 // if init and step are unreachable, cond is unreachable, too
5964 if (!stmt->base.reachable && !fors->step_reachable) {
5965 warningf(&stmt->base.source_position, "statement is unreachable");
5967 if (!stmt->base.reachable && fors->initialisation != NULL) {
5968 warningf(&fors->initialisation->base.source_position,
5969 "initialisation of for-statement is unreachable");
5972 if (!fors->condition_reachable && fors->condition != NULL) {
5973 warningf(&fors->condition->base.source_position,
5974 "condition of for-statement is unreachable");
5977 if (!fors->step_reachable && fors->step != NULL) {
5978 warningf(&fors->step->base.source_position,
5979 "step of for-statement is unreachable");
5985 case STATEMENT_COMPOUND:
5986 if (stmt->compound.statements != NULL)
5991 if (!stmt->base.reachable)
5992 warningf(&stmt->base.source_position, "statement is unreachable");
5997 static void parse_external_declaration(void)
5999 /* function-definitions and declarations both start with declaration
6001 declaration_specifiers_t specifiers;
6002 memset(&specifiers, 0, sizeof(specifiers));
6004 add_anchor_token(';');
6005 parse_declaration_specifiers(&specifiers);
6006 rem_anchor_token(';');
6008 /* must be a declaration */
6009 if (token.type == ';') {
6010 parse_anonymous_declaration_rest(&specifiers);
6014 add_anchor_token(',');
6015 add_anchor_token('=');
6016 add_anchor_token(';');
6017 add_anchor_token('{');
6019 /* declarator is common to both function-definitions and declarations */
6020 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
6022 rem_anchor_token('{');
6023 rem_anchor_token(';');
6024 rem_anchor_token('=');
6025 rem_anchor_token(',');
6027 /* must be a declaration */
6028 switch (token.type) {
6032 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
6036 /* must be a function definition */
6037 parse_kr_declaration_list(ndeclaration);
6039 if (token.type != '{') {
6040 parse_error_expected("while parsing function definition", '{', NULL);
6041 eat_until_matching_token(';');
6045 assert(is_declaration(ndeclaration));
6046 type_t *type = skip_typeref(ndeclaration->declaration.type);
6048 if (!is_type_function(type)) {
6049 if (is_type_valid(type)) {
6050 errorf(HERE, "declarator '%#T' has a body but is not a function type",
6051 type, ndeclaration->base.symbol);
6057 if (warning.aggregate_return &&
6058 is_type_compound(skip_typeref(type->function.return_type))) {
6059 warningf(HERE, "function '%Y' returns an aggregate",
6060 ndeclaration->base.symbol);
6062 if (warning.traditional && !type->function.unspecified_parameters) {
6063 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
6064 ndeclaration->base.symbol);
6066 if (warning.old_style_definition && type->function.unspecified_parameters) {
6067 warningf(HERE, "old-style function definition '%Y'",
6068 ndeclaration->base.symbol);
6071 /* § 6.7.5.3 (14) a function definition with () means no
6072 * parameters (and not unspecified parameters) */
6073 if (type->function.unspecified_parameters
6074 && type->function.parameters == NULL
6075 && !type->function.kr_style_parameters) {
6076 type_t *duplicate = duplicate_type(type);
6077 duplicate->function.unspecified_parameters = false;
6079 type = typehash_insert(duplicate);
6080 if (type != duplicate) {
6081 obstack_free(type_obst, duplicate);
6083 ndeclaration->declaration.type = type;
6086 entity_t *const entity = record_entity(ndeclaration, true);
6087 assert(entity->kind == ENTITY_FUNCTION);
6088 assert(ndeclaration->kind == ENTITY_FUNCTION);
6090 function_t *function = &entity->function;
6091 if (ndeclaration != entity) {
6092 function->parameters = ndeclaration->function.parameters;
6094 assert(is_declaration(entity));
6095 type = skip_typeref(entity->declaration.type);
6097 /* push function parameters and switch scope */
6098 size_t const top = environment_top();
6099 scope_push(&function->parameters);
6101 entity_t *parameter = function->parameters.entities;
6102 for (; parameter != NULL; parameter = parameter->base.next) {
6103 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
6104 parameter->base.parent_scope = current_scope;
6106 assert(parameter->base.parent_scope == NULL
6107 || parameter->base.parent_scope == current_scope);
6108 parameter->base.parent_scope = current_scope;
6109 if (parameter->base.symbol == NULL) {
6110 errorf(¶meter->base.source_position, "parameter name omitted");
6113 environment_push(parameter);
6116 if (function->statement != NULL) {
6117 parser_error_multiple_definition(entity, HERE);
6120 /* parse function body */
6121 int label_stack_top = label_top();
6122 function_t *old_current_function = current_function;
6123 current_function = function;
6124 current_parent = NULL;
6127 goto_anchor = &goto_first;
6129 label_anchor = &label_first;
6131 statement_t *const body = parse_compound_statement(false);
6132 function->statement = body;
6135 check_declarations();
6136 if (warning.return_type ||
6137 warning.unreachable_code ||
6138 (warning.missing_noreturn
6139 && !(function->base.modifiers & DM_NORETURN))) {
6140 noreturn_candidate = true;
6141 check_reachable(body);
6142 if (warning.unreachable_code)
6143 walk_statements(body, check_unreachable, NULL);
6144 if (warning.missing_noreturn &&
6145 noreturn_candidate &&
6146 !(function->base.modifiers & DM_NORETURN)) {
6147 warningf(&body->base.source_position,
6148 "function '%#T' is candidate for attribute 'noreturn'",
6149 type, entity->base.symbol);
6153 assert(current_parent == NULL);
6154 assert(current_function == function);
6155 current_function = old_current_function;
6156 label_pop_to(label_stack_top);
6159 assert(current_scope == &function->parameters);
6161 environment_pop_to(top);
6164 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
6165 source_position_t *source_position,
6166 const symbol_t *symbol)
6168 type_t *type = allocate_type_zero(TYPE_BITFIELD);
6170 type->bitfield.base_type = base_type;
6171 type->bitfield.size_expression = size;
6174 type_t *skipped_type = skip_typeref(base_type);
6175 if (!is_type_integer(skipped_type)) {
6176 errorf(HERE, "bitfield base type '%T' is not an integer type",
6180 bit_size = skipped_type->base.size * 8;
6183 if (is_constant_expression(size)) {
6184 long v = fold_constant(size);
6187 errorf(source_position, "negative width in bit-field '%Y'", symbol);
6188 } else if (v == 0) {
6189 errorf(source_position, "zero width for bit-field '%Y'", symbol);
6190 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6191 errorf(source_position, "width of '%Y' exceeds its type", symbol);
6193 type->bitfield.bit_size = v;
6200 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6202 entity_t *iter = compound->members.entities;
6203 for (; iter != NULL; iter = iter->base.next) {
6204 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6207 if (iter->base.symbol == symbol) {
6209 } else if (iter->base.symbol == NULL) {
6210 type_t *type = skip_typeref(iter->declaration.type);
6211 if (is_type_compound(type)) {
6213 = find_compound_entry(type->compound.compound, symbol);
6224 static void parse_compound_declarators(compound_t *compound,
6225 const declaration_specifiers_t *specifiers)
6230 if (token.type == ':') {
6231 source_position_t source_position = *HERE;
6234 type_t *base_type = specifiers->type;
6235 expression_t *size = parse_constant_expression();
6237 type_t *type = make_bitfield_type(base_type, size,
6238 &source_position, sym_anonymous);
6240 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6241 entity->base.namespc = NAMESPACE_NORMAL;
6242 entity->base.source_position = source_position;
6243 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6244 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6245 entity->declaration.modifiers = specifiers->modifiers;
6246 entity->declaration.type = type;
6248 entity = parse_declarator(specifiers,
6249 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
6250 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6252 if (token.type == ':') {
6253 source_position_t source_position = *HERE;
6255 expression_t *size = parse_constant_expression();
6257 type_t *type = entity->declaration.type;
6258 type_t *bitfield_type = make_bitfield_type(type, size,
6259 &source_position, entity->base.symbol);
6260 entity->declaration.type = bitfield_type;
6264 /* make sure we don't define a symbol multiple times */
6265 symbol_t *symbol = entity->base.symbol;
6266 if (symbol != NULL) {
6267 entity_t *prev = find_compound_entry(compound, symbol);
6270 errorf(&entity->base.source_position,
6271 "multiple declarations of symbol '%Y' (declared %P)",
6272 symbol, &prev->base.source_position);
6276 append_entity(&compound->members, entity);
6278 type_t *orig_type = entity->declaration.type;
6279 type_t *type = skip_typeref(orig_type);
6280 if (is_type_function(type)) {
6281 errorf(&entity->base.source_position,
6282 "compound member '%Y' must not have function type '%T'",
6283 entity->base.symbol, orig_type);
6284 } else if (is_type_incomplete(type)) {
6285 /* §6.7.2.1:16 flexible array member */
6286 if (is_type_array(type) &&
6287 token.type == ';' &&
6288 look_ahead(1)->type == '}') {
6289 compound->has_flexible_member = true;
6291 errorf(&entity->base.source_position,
6292 "compound member '%Y' has incomplete type '%T'",
6293 entity->base.symbol, orig_type);
6297 if (token.type != ',')
6304 anonymous_entity = NULL;
6307 static void parse_compound_type_entries(compound_t *compound)
6310 add_anchor_token('}');
6312 while (token.type != '}') {
6313 if (token.type == T_EOF) {
6314 errorf(HERE, "EOF while parsing struct");
6317 declaration_specifiers_t specifiers;
6318 memset(&specifiers, 0, sizeof(specifiers));
6319 parse_declaration_specifiers(&specifiers);
6321 parse_compound_declarators(compound, &specifiers);
6323 rem_anchor_token('}');
6327 compound->complete = true;
6330 static type_t *parse_typename(void)
6332 declaration_specifiers_t specifiers;
6333 memset(&specifiers, 0, sizeof(specifiers));
6334 parse_declaration_specifiers(&specifiers);
6335 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6336 /* TODO: improve error message, user does probably not know what a
6337 * storage class is...
6339 errorf(HERE, "typename may not have a storage class");
6342 type_t *result = parse_abstract_declarator(specifiers.type);
6350 typedef expression_t* (*parse_expression_function)(void);
6351 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6353 typedef struct expression_parser_function_t expression_parser_function_t;
6354 struct expression_parser_function_t {
6355 parse_expression_function parser;
6356 unsigned infix_precedence;
6357 parse_expression_infix_function infix_parser;
6360 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6363 * Prints an error message if an expression was expected but not read
6365 static expression_t *expected_expression_error(void)
6367 /* skip the error message if the error token was read */
6368 if (token.type != T_ERROR) {
6369 errorf(HERE, "expected expression, got token '%K'", &token);
6373 return create_invalid_expression();
6377 * Parse a string constant.
6379 static expression_t *parse_string_const(void)
6382 if (token.type == T_STRING_LITERAL) {
6383 string_t res = token.v.string;
6385 while (token.type == T_STRING_LITERAL) {
6386 res = concat_strings(&res, &token.v.string);
6389 if (token.type != T_WIDE_STRING_LITERAL) {
6390 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6391 /* note: that we use type_char_ptr here, which is already the
6392 * automatic converted type. revert_automatic_type_conversion
6393 * will construct the array type */
6394 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6395 cnst->string.value = res;
6399 wres = concat_string_wide_string(&res, &token.v.wide_string);
6401 wres = token.v.wide_string;
6406 switch (token.type) {
6407 case T_WIDE_STRING_LITERAL:
6408 wres = concat_wide_strings(&wres, &token.v.wide_string);
6411 case T_STRING_LITERAL:
6412 wres = concat_wide_string_string(&wres, &token.v.string);
6416 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6417 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6418 cnst->wide_string.value = wres;
6427 * Parse a boolean constant.
6429 static expression_t *parse_bool_const(bool value)
6431 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6432 cnst->base.type = type_bool;
6433 cnst->conste.v.int_value = value;
6441 * Parse an integer constant.
6443 static expression_t *parse_int_const(void)
6445 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6446 cnst->base.type = token.datatype;
6447 cnst->conste.v.int_value = token.v.intvalue;
6455 * Parse a character constant.
6457 static expression_t *parse_character_constant(void)
6459 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6460 cnst->base.type = token.datatype;
6461 cnst->conste.v.character = token.v.string;
6463 if (cnst->conste.v.character.size != 1) {
6465 errorf(HERE, "more than 1 character in character constant");
6466 } else if (warning.multichar) {
6467 warningf(HERE, "multi-character character constant");
6476 * Parse a wide character constant.
6478 static expression_t *parse_wide_character_constant(void)
6480 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6481 cnst->base.type = token.datatype;
6482 cnst->conste.v.wide_character = token.v.wide_string;
6484 if (cnst->conste.v.wide_character.size != 1) {
6486 errorf(HERE, "more than 1 character in character constant");
6487 } else if (warning.multichar) {
6488 warningf(HERE, "multi-character character constant");
6497 * Parse a float constant.
6499 static expression_t *parse_float_const(void)
6501 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6502 cnst->base.type = token.datatype;
6503 cnst->conste.v.float_value = token.v.floatvalue;
6510 static entity_t *create_implicit_function(symbol_t *symbol,
6511 const source_position_t *source_position)
6513 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6514 ntype->function.return_type = type_int;
6515 ntype->function.unspecified_parameters = true;
6517 type_t *type = typehash_insert(ntype);
6518 if (type != ntype) {
6522 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6523 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6524 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6525 entity->declaration.type = type;
6526 entity->declaration.implicit = true;
6527 entity->base.symbol = symbol;
6528 entity->base.source_position = *source_position;
6530 bool strict_prototypes_old = warning.strict_prototypes;
6531 warning.strict_prototypes = false;
6532 record_entity(entity, false);
6533 warning.strict_prototypes = strict_prototypes_old;
6539 * Creates a return_type (func)(argument_type) function type if not
6542 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6543 type_t *argument_type2)
6545 function_parameter_t *parameter2
6546 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6547 memset(parameter2, 0, sizeof(parameter2[0]));
6548 parameter2->type = argument_type2;
6550 function_parameter_t *parameter1
6551 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6552 memset(parameter1, 0, sizeof(parameter1[0]));
6553 parameter1->type = argument_type1;
6554 parameter1->next = parameter2;
6556 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6557 type->function.return_type = return_type;
6558 type->function.parameters = parameter1;
6560 type_t *result = typehash_insert(type);
6561 if (result != type) {
6569 * Creates a return_type (func)(argument_type) function type if not
6572 * @param return_type the return type
6573 * @param argument_type the argument type
6575 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6577 function_parameter_t *parameter
6578 = obstack_alloc(type_obst, sizeof(parameter[0]));
6579 memset(parameter, 0, sizeof(parameter[0]));
6580 parameter->type = argument_type;
6582 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6583 type->function.return_type = return_type;
6584 type->function.parameters = parameter;
6586 type_t *result = typehash_insert(type);
6587 if (result != type) {
6594 static type_t *make_function_0_type(type_t *return_type)
6596 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6597 type->function.return_type = return_type;
6598 type->function.parameters = NULL;
6600 type_t *result = typehash_insert(type);
6601 if (result != type) {
6609 * Creates a function type for some function like builtins.
6611 * @param symbol the symbol describing the builtin
6613 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6615 switch (symbol->ID) {
6616 case T___builtin_alloca:
6617 return make_function_1_type(type_void_ptr, type_size_t);
6618 case T___builtin_huge_val:
6619 return make_function_0_type(type_double);
6620 case T___builtin_inf:
6621 return make_function_0_type(type_double);
6622 case T___builtin_inff:
6623 return make_function_0_type(type_float);
6624 case T___builtin_infl:
6625 return make_function_0_type(type_long_double);
6626 case T___builtin_nan:
6627 return make_function_1_type(type_double, type_char_ptr);
6628 case T___builtin_nanf:
6629 return make_function_1_type(type_float, type_char_ptr);
6630 case T___builtin_nanl:
6631 return make_function_1_type(type_long_double, type_char_ptr);
6632 case T___builtin_va_end:
6633 return make_function_1_type(type_void, type_valist);
6634 case T___builtin_expect:
6635 return make_function_2_type(type_long, type_long, type_long);
6637 internal_errorf(HERE, "not implemented builtin symbol found");
6642 * Performs automatic type cast as described in § 6.3.2.1.
6644 * @param orig_type the original type
6646 static type_t *automatic_type_conversion(type_t *orig_type)
6648 type_t *type = skip_typeref(orig_type);
6649 if (is_type_array(type)) {
6650 array_type_t *array_type = &type->array;
6651 type_t *element_type = array_type->element_type;
6652 unsigned qualifiers = array_type->base.qualifiers;
6654 return make_pointer_type(element_type, qualifiers);
6657 if (is_type_function(type)) {
6658 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6665 * reverts the automatic casts of array to pointer types and function
6666 * to function-pointer types as defined § 6.3.2.1
6668 type_t *revert_automatic_type_conversion(const expression_t *expression)
6670 switch (expression->kind) {
6671 case EXPR_REFERENCE: {
6672 entity_t *entity = expression->reference.entity;
6673 if (is_declaration(entity)) {
6674 return entity->declaration.type;
6675 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6676 return entity->enum_value.enum_type;
6678 panic("no declaration or enum in reference");
6683 entity_t *entity = expression->select.compound_entry;
6684 assert(is_declaration(entity));
6685 type_t *type = entity->declaration.type;
6686 return get_qualified_type(type,
6687 expression->base.type->base.qualifiers);
6690 case EXPR_UNARY_DEREFERENCE: {
6691 const expression_t *const value = expression->unary.value;
6692 type_t *const type = skip_typeref(value->base.type);
6693 assert(is_type_pointer(type));
6694 return type->pointer.points_to;
6697 case EXPR_BUILTIN_SYMBOL:
6698 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6700 case EXPR_ARRAY_ACCESS: {
6701 const expression_t *array_ref = expression->array_access.array_ref;
6702 type_t *type_left = skip_typeref(array_ref->base.type);
6703 if (!is_type_valid(type_left))
6705 assert(is_type_pointer(type_left));
6706 return type_left->pointer.points_to;
6709 case EXPR_STRING_LITERAL: {
6710 size_t size = expression->string.value.size;
6711 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6714 case EXPR_WIDE_STRING_LITERAL: {
6715 size_t size = expression->wide_string.value.size;
6716 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6719 case EXPR_COMPOUND_LITERAL:
6720 return expression->compound_literal.type;
6725 return expression->base.type;
6728 static expression_t *parse_reference(void)
6730 symbol_t *const symbol = token.v.symbol;
6732 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6734 if (entity == NULL) {
6735 if (!strict_mode && look_ahead(1)->type == '(') {
6736 /* an implicitly declared function */
6737 if (warning.implicit_function_declaration) {
6738 warningf(HERE, "implicit declaration of function '%Y'",
6742 entity = create_implicit_function(symbol, HERE);
6744 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6745 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6751 if (is_declaration(entity)) {
6752 orig_type = entity->declaration.type;
6753 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6754 orig_type = entity->enum_value.enum_type;
6755 } else if (entity->kind == ENTITY_TYPEDEF) {
6756 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6759 return create_invalid_expression();
6761 panic("expected declaration or enum value in reference");
6764 /* we always do the auto-type conversions; the & and sizeof parser contains
6765 * code to revert this! */
6766 type_t *type = automatic_type_conversion(orig_type);
6768 expression_kind_t kind = EXPR_REFERENCE;
6769 if (entity->kind == ENTITY_ENUM_VALUE)
6770 kind = EXPR_REFERENCE_ENUM_VALUE;
6772 expression_t *expression = allocate_expression_zero(kind);
6773 expression->reference.entity = entity;
6774 expression->base.type = type;
6776 /* this declaration is used */
6777 if (is_declaration(entity)) {
6778 entity->declaration.used = true;
6781 if (entity->base.parent_scope != file_scope
6782 && entity->base.parent_scope->depth < current_function->parameters.depth
6783 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6784 if (entity->kind == ENTITY_VARIABLE) {
6785 /* access of a variable from an outer function */
6786 entity->variable.address_taken = true;
6788 current_function->need_closure = true;
6791 /* check for deprecated functions */
6792 if (warning.deprecated_declarations
6793 && is_declaration(entity)
6794 && entity->declaration.modifiers & DM_DEPRECATED) {
6795 declaration_t *declaration = &entity->declaration;
6797 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6798 "function" : "variable";
6800 if (declaration->deprecated_string != NULL) {
6801 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6802 prefix, entity->base.symbol, &entity->base.source_position,
6803 declaration->deprecated_string);
6805 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6806 entity->base.symbol, &entity->base.source_position);
6810 if (warning.init_self && entity == current_init_decl && !in_type_prop
6811 && entity->kind == ENTITY_VARIABLE) {
6812 current_init_decl = NULL;
6813 warningf(HERE, "variable '%#T' is initialized by itself",
6814 entity->declaration.type, entity->base.symbol);
6821 static bool semantic_cast(expression_t *cast)
6823 expression_t *expression = cast->unary.value;
6824 type_t *orig_dest_type = cast->base.type;
6825 type_t *orig_type_right = expression->base.type;
6826 type_t const *dst_type = skip_typeref(orig_dest_type);
6827 type_t const *src_type = skip_typeref(orig_type_right);
6828 source_position_t const *pos = &cast->base.source_position;
6830 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6831 if (dst_type == type_void)
6834 /* only integer and pointer can be casted to pointer */
6835 if (is_type_pointer(dst_type) &&
6836 !is_type_pointer(src_type) &&
6837 !is_type_integer(src_type) &&
6838 is_type_valid(src_type)) {
6839 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6843 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6844 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6848 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6849 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6853 if (warning.cast_qual &&
6854 is_type_pointer(src_type) &&
6855 is_type_pointer(dst_type)) {
6856 type_t *src = skip_typeref(src_type->pointer.points_to);
6857 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6858 unsigned missing_qualifiers =
6859 src->base.qualifiers & ~dst->base.qualifiers;
6860 if (missing_qualifiers != 0) {
6862 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6863 missing_qualifiers, orig_type_right);
6869 static expression_t *parse_compound_literal(type_t *type)
6871 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6873 parse_initializer_env_t env;
6876 env.must_be_constant = false;
6877 initializer_t *initializer = parse_initializer(&env);
6880 expression->compound_literal.initializer = initializer;
6881 expression->compound_literal.type = type;
6882 expression->base.type = automatic_type_conversion(type);
6888 * Parse a cast expression.
6890 static expression_t *parse_cast(void)
6892 add_anchor_token(')');
6894 source_position_t source_position = token.source_position;
6896 type_t *type = parse_typename();
6898 rem_anchor_token(')');
6901 if (token.type == '{') {
6902 return parse_compound_literal(type);
6905 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6906 cast->base.source_position = source_position;
6908 expression_t *value = parse_sub_expression(PREC_CAST);
6909 cast->base.type = type;
6910 cast->unary.value = value;
6912 if (! semantic_cast(cast)) {
6913 /* TODO: record the error in the AST. else it is impossible to detect it */
6918 return create_invalid_expression();
6922 * Parse a statement expression.
6924 static expression_t *parse_statement_expression(void)
6926 add_anchor_token(')');
6928 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6930 statement_t *statement = parse_compound_statement(true);
6931 expression->statement.statement = statement;
6933 /* find last statement and use its type */
6934 type_t *type = type_void;
6935 const statement_t *stmt = statement->compound.statements;
6937 while (stmt->base.next != NULL)
6938 stmt = stmt->base.next;
6940 if (stmt->kind == STATEMENT_EXPRESSION) {
6941 type = stmt->expression.expression->base.type;
6943 } else if (warning.other) {
6944 warningf(&expression->base.source_position, "empty statement expression ({})");
6946 expression->base.type = type;
6948 rem_anchor_token(')');
6956 * Parse a parenthesized expression.
6958 static expression_t *parse_parenthesized_expression(void)
6962 switch (token.type) {
6964 /* gcc extension: a statement expression */
6965 return parse_statement_expression();
6969 return parse_cast();
6971 if (is_typedef_symbol(token.v.symbol)) {
6972 return parse_cast();
6976 add_anchor_token(')');
6977 expression_t *result = parse_expression();
6978 rem_anchor_token(')');
6985 static expression_t *parse_function_keyword(void)
6989 if (current_function == NULL) {
6990 errorf(HERE, "'__func__' used outside of a function");
6993 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6994 expression->base.type = type_char_ptr;
6995 expression->funcname.kind = FUNCNAME_FUNCTION;
7002 static expression_t *parse_pretty_function_keyword(void)
7004 if (current_function == NULL) {
7005 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
7008 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7009 expression->base.type = type_char_ptr;
7010 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
7012 eat(T___PRETTY_FUNCTION__);
7017 static expression_t *parse_funcsig_keyword(void)
7019 if (current_function == NULL) {
7020 errorf(HERE, "'__FUNCSIG__' used outside of a function");
7023 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7024 expression->base.type = type_char_ptr;
7025 expression->funcname.kind = FUNCNAME_FUNCSIG;
7032 static expression_t *parse_funcdname_keyword(void)
7034 if (current_function == NULL) {
7035 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
7038 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
7039 expression->base.type = type_char_ptr;
7040 expression->funcname.kind = FUNCNAME_FUNCDNAME;
7042 eat(T___FUNCDNAME__);
7047 static designator_t *parse_designator(void)
7049 designator_t *result = allocate_ast_zero(sizeof(result[0]));
7050 result->source_position = *HERE;
7052 if (token.type != T_IDENTIFIER) {
7053 parse_error_expected("while parsing member designator",
7054 T_IDENTIFIER, NULL);
7057 result->symbol = token.v.symbol;
7060 designator_t *last_designator = result;
7062 if (token.type == '.') {
7064 if (token.type != T_IDENTIFIER) {
7065 parse_error_expected("while parsing member designator",
7066 T_IDENTIFIER, NULL);
7069 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7070 designator->source_position = *HERE;
7071 designator->symbol = token.v.symbol;
7074 last_designator->next = designator;
7075 last_designator = designator;
7078 if (token.type == '[') {
7080 add_anchor_token(']');
7081 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
7082 designator->source_position = *HERE;
7083 designator->array_index = parse_expression();
7084 rem_anchor_token(']');
7086 if (designator->array_index == NULL) {
7090 last_designator->next = designator;
7091 last_designator = designator;
7103 * Parse the __builtin_offsetof() expression.
7105 static expression_t *parse_offsetof(void)
7107 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
7108 expression->base.type = type_size_t;
7110 eat(T___builtin_offsetof);
7113 add_anchor_token(',');
7114 type_t *type = parse_typename();
7115 rem_anchor_token(',');
7117 add_anchor_token(')');
7118 designator_t *designator = parse_designator();
7119 rem_anchor_token(')');
7122 expression->offsetofe.type = type;
7123 expression->offsetofe.designator = designator;
7126 memset(&path, 0, sizeof(path));
7127 path.top_type = type;
7128 path.path = NEW_ARR_F(type_path_entry_t, 0);
7130 descend_into_subtype(&path);
7132 if (!walk_designator(&path, designator, true)) {
7133 return create_invalid_expression();
7136 DEL_ARR_F(path.path);
7140 return create_invalid_expression();
7144 * Parses a _builtin_va_start() expression.
7146 static expression_t *parse_va_start(void)
7148 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
7150 eat(T___builtin_va_start);
7153 add_anchor_token(',');
7154 expression->va_starte.ap = parse_assignment_expression();
7155 rem_anchor_token(',');
7157 expression_t *const expr = parse_assignment_expression();
7158 if (expr->kind == EXPR_REFERENCE) {
7159 entity_t *const entity = expr->reference.entity;
7160 if (entity->base.parent_scope != ¤t_function->parameters
7161 || entity->base.next != NULL
7162 || entity->kind != ENTITY_VARIABLE) {
7163 errorf(&expr->base.source_position,
7164 "second argument of 'va_start' must be last parameter of the current function");
7166 expression->va_starte.parameter = &entity->variable;
7173 return create_invalid_expression();
7177 * Parses a _builtin_va_arg() expression.
7179 static expression_t *parse_va_arg(void)
7181 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7183 eat(T___builtin_va_arg);
7186 expression->va_arge.ap = parse_assignment_expression();
7188 expression->base.type = parse_typename();
7193 return create_invalid_expression();
7196 static expression_t *parse_builtin_symbol(void)
7198 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7200 symbol_t *symbol = token.v.symbol;
7202 expression->builtin_symbol.symbol = symbol;
7205 type_t *type = get_builtin_symbol_type(symbol);
7206 type = automatic_type_conversion(type);
7208 expression->base.type = type;
7213 * Parses a __builtin_constant() expression.
7215 static expression_t *parse_builtin_constant(void)
7217 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7219 eat(T___builtin_constant_p);
7222 add_anchor_token(')');
7223 expression->builtin_constant.value = parse_assignment_expression();
7224 rem_anchor_token(')');
7226 expression->base.type = type_int;
7230 return create_invalid_expression();
7234 * Parses a __builtin_prefetch() expression.
7236 static expression_t *parse_builtin_prefetch(void)
7238 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7240 eat(T___builtin_prefetch);
7243 add_anchor_token(')');
7244 expression->builtin_prefetch.adr = parse_assignment_expression();
7245 if (token.type == ',') {
7247 expression->builtin_prefetch.rw = parse_assignment_expression();
7249 if (token.type == ',') {
7251 expression->builtin_prefetch.locality = parse_assignment_expression();
7253 rem_anchor_token(')');
7255 expression->base.type = type_void;
7259 return create_invalid_expression();
7263 * Parses a __builtin_is_*() compare expression.
7265 static expression_t *parse_compare_builtin(void)
7267 expression_t *expression;
7269 switch (token.type) {
7270 case T___builtin_isgreater:
7271 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7273 case T___builtin_isgreaterequal:
7274 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7276 case T___builtin_isless:
7277 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7279 case T___builtin_islessequal:
7280 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7282 case T___builtin_islessgreater:
7283 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7285 case T___builtin_isunordered:
7286 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7289 internal_errorf(HERE, "invalid compare builtin found");
7291 expression->base.source_position = *HERE;
7295 expression->binary.left = parse_assignment_expression();
7297 expression->binary.right = parse_assignment_expression();
7300 type_t *const orig_type_left = expression->binary.left->base.type;
7301 type_t *const orig_type_right = expression->binary.right->base.type;
7303 type_t *const type_left = skip_typeref(orig_type_left);
7304 type_t *const type_right = skip_typeref(orig_type_right);
7305 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7306 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7307 type_error_incompatible("invalid operands in comparison",
7308 &expression->base.source_position, orig_type_left, orig_type_right);
7311 semantic_comparison(&expression->binary);
7316 return create_invalid_expression();
7321 * Parses a __builtin_expect() expression.
7323 static expression_t *parse_builtin_expect(void)
7325 expression_t *expression
7326 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7328 eat(T___builtin_expect);
7331 expression->binary.left = parse_assignment_expression();
7333 expression->binary.right = parse_constant_expression();
7336 expression->base.type = expression->binary.left->base.type;
7340 return create_invalid_expression();
7345 * Parses a MS assume() expression.
7347 static expression_t *parse_assume(void)
7349 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7354 add_anchor_token(')');
7355 expression->unary.value = parse_assignment_expression();
7356 rem_anchor_token(')');
7359 expression->base.type = type_void;
7362 return create_invalid_expression();
7366 * Return the declaration for a given label symbol or create a new one.
7368 * @param symbol the symbol of the label
7370 static label_t *get_label(symbol_t *symbol)
7373 assert(current_function != NULL);
7375 label = get_entity(symbol, NAMESPACE_LABEL);
7376 /* if we found a local label, we already created the declaration */
7377 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7378 if (label->base.parent_scope != current_scope) {
7379 assert(label->base.parent_scope->depth < current_scope->depth);
7380 current_function->goto_to_outer = true;
7382 return &label->label;
7385 label = get_entity(symbol, NAMESPACE_LABEL);
7386 /* if we found a label in the same function, then we already created the
7389 && label->base.parent_scope == ¤t_function->parameters) {
7390 return &label->label;
7393 /* otherwise we need to create a new one */
7394 label = allocate_entity_zero(ENTITY_LABEL);
7395 label->base.namespc = NAMESPACE_LABEL;
7396 label->base.symbol = symbol;
7400 return &label->label;
7404 * Parses a GNU && label address expression.
7406 static expression_t *parse_label_address(void)
7408 source_position_t source_position = token.source_position;
7410 if (token.type != T_IDENTIFIER) {
7411 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7414 symbol_t *symbol = token.v.symbol;
7417 label_t *label = get_label(symbol);
7419 label->address_taken = true;
7421 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7422 expression->base.source_position = source_position;
7424 /* label address is threaten as a void pointer */
7425 expression->base.type = type_void_ptr;
7426 expression->label_address.label = label;
7429 return create_invalid_expression();
7433 * Parse a microsoft __noop expression.
7435 static expression_t *parse_noop_expression(void)
7437 /* the result is a (int)0 */
7438 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7439 cnst->base.type = type_int;
7440 cnst->conste.v.int_value = 0;
7441 cnst->conste.is_ms_noop = true;
7445 if (token.type == '(') {
7446 /* parse arguments */
7448 add_anchor_token(')');
7449 add_anchor_token(',');
7451 if (token.type != ')') {
7453 (void)parse_assignment_expression();
7454 if (token.type != ',')
7460 rem_anchor_token(',');
7461 rem_anchor_token(')');
7469 * Parses a primary expression.
7471 static expression_t *parse_primary_expression(void)
7473 switch (token.type) {
7474 case T_false: return parse_bool_const(false);
7475 case T_true: return parse_bool_const(true);
7476 case T_INTEGER: return parse_int_const();
7477 case T_CHARACTER_CONSTANT: return parse_character_constant();
7478 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7479 case T_FLOATINGPOINT: return parse_float_const();
7480 case T_STRING_LITERAL:
7481 case T_WIDE_STRING_LITERAL: return parse_string_const();
7482 case T_IDENTIFIER: return parse_reference();
7483 case T___FUNCTION__:
7484 case T___func__: return parse_function_keyword();
7485 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7486 case T___FUNCSIG__: return parse_funcsig_keyword();
7487 case T___FUNCDNAME__: return parse_funcdname_keyword();
7488 case T___builtin_offsetof: return parse_offsetof();
7489 case T___builtin_va_start: return parse_va_start();
7490 case T___builtin_va_arg: return parse_va_arg();
7491 case T___builtin_expect:
7492 case T___builtin_alloca:
7493 case T___builtin_inf:
7494 case T___builtin_inff:
7495 case T___builtin_infl:
7496 case T___builtin_nan:
7497 case T___builtin_nanf:
7498 case T___builtin_nanl:
7499 case T___builtin_huge_val:
7500 case T___builtin_va_end: return parse_builtin_symbol();
7501 case T___builtin_isgreater:
7502 case T___builtin_isgreaterequal:
7503 case T___builtin_isless:
7504 case T___builtin_islessequal:
7505 case T___builtin_islessgreater:
7506 case T___builtin_isunordered: return parse_compare_builtin();
7507 case T___builtin_constant_p: return parse_builtin_constant();
7508 case T___builtin_prefetch: return parse_builtin_prefetch();
7509 case T__assume: return parse_assume();
7512 return parse_label_address();
7515 case '(': return parse_parenthesized_expression();
7516 case T___noop: return parse_noop_expression();
7519 errorf(HERE, "unexpected token %K, expected an expression", &token);
7520 return create_invalid_expression();
7524 * Check if the expression has the character type and issue a warning then.
7526 static void check_for_char_index_type(const expression_t *expression)
7528 type_t *const type = expression->base.type;
7529 const type_t *const base_type = skip_typeref(type);
7531 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7532 warning.char_subscripts) {
7533 warningf(&expression->base.source_position,
7534 "array subscript has type '%T'", type);
7538 static expression_t *parse_array_expression(expression_t *left)
7540 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7543 add_anchor_token(']');
7545 expression_t *inside = parse_expression();
7547 type_t *const orig_type_left = left->base.type;
7548 type_t *const orig_type_inside = inside->base.type;
7550 type_t *const type_left = skip_typeref(orig_type_left);
7551 type_t *const type_inside = skip_typeref(orig_type_inside);
7553 type_t *return_type;
7554 array_access_expression_t *array_access = &expression->array_access;
7555 if (is_type_pointer(type_left)) {
7556 return_type = type_left->pointer.points_to;
7557 array_access->array_ref = left;
7558 array_access->index = inside;
7559 check_for_char_index_type(inside);
7560 } else if (is_type_pointer(type_inside)) {
7561 return_type = type_inside->pointer.points_to;
7562 array_access->array_ref = inside;
7563 array_access->index = left;
7564 array_access->flipped = true;
7565 check_for_char_index_type(left);
7567 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7569 "array access on object with non-pointer types '%T', '%T'",
7570 orig_type_left, orig_type_inside);
7572 return_type = type_error_type;
7573 array_access->array_ref = left;
7574 array_access->index = inside;
7577 expression->base.type = automatic_type_conversion(return_type);
7579 rem_anchor_token(']');
7585 static expression_t *parse_typeprop(expression_kind_t const kind)
7587 expression_t *tp_expression = allocate_expression_zero(kind);
7588 tp_expression->base.type = type_size_t;
7590 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7592 /* we only refer to a type property, mark this case */
7593 bool old = in_type_prop;
7594 in_type_prop = true;
7597 expression_t *expression;
7598 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7600 add_anchor_token(')');
7601 orig_type = parse_typename();
7602 rem_anchor_token(')');
7605 if (token.type == '{') {
7606 /* It was not sizeof(type) after all. It is sizeof of an expression
7607 * starting with a compound literal */
7608 expression = parse_compound_literal(orig_type);
7609 goto typeprop_expression;
7612 expression = parse_sub_expression(PREC_UNARY);
7614 typeprop_expression:
7615 tp_expression->typeprop.tp_expression = expression;
7617 orig_type = revert_automatic_type_conversion(expression);
7618 expression->base.type = orig_type;
7621 tp_expression->typeprop.type = orig_type;
7622 type_t const* const type = skip_typeref(orig_type);
7623 char const* const wrong_type =
7624 is_type_incomplete(type) ? "incomplete" :
7625 type->kind == TYPE_FUNCTION ? "function designator" :
7626 type->kind == TYPE_BITFIELD ? "bitfield" :
7628 if (wrong_type != NULL) {
7629 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7630 errorf(&tp_expression->base.source_position,
7631 "operand of %s expression must not be of %s type '%T'",
7632 what, wrong_type, orig_type);
7637 return tp_expression;
7640 static expression_t *parse_sizeof(void)
7642 return parse_typeprop(EXPR_SIZEOF);
7645 static expression_t *parse_alignof(void)
7647 return parse_typeprop(EXPR_ALIGNOF);
7650 static expression_t *parse_select_expression(expression_t *compound)
7652 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7653 select->select.compound = compound;
7655 assert(token.type == '.' || token.type == T_MINUSGREATER);
7656 bool is_pointer = (token.type == T_MINUSGREATER);
7659 if (token.type != T_IDENTIFIER) {
7660 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7663 symbol_t *symbol = token.v.symbol;
7666 type_t *const orig_type = compound->base.type;
7667 type_t *const type = skip_typeref(orig_type);
7670 bool saw_error = false;
7671 if (is_type_pointer(type)) {
7674 "request for member '%Y' in something not a struct or union, but '%T'",
7678 type_left = skip_typeref(type->pointer.points_to);
7680 if (is_pointer && is_type_valid(type)) {
7681 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7688 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7689 type_left->kind == TYPE_COMPOUND_UNION) {
7690 compound_t *compound = type_left->compound.compound;
7692 if (!compound->complete) {
7693 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7695 goto create_error_entry;
7698 entry = find_compound_entry(compound, symbol);
7699 if (entry == NULL) {
7700 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7701 goto create_error_entry;
7704 if (is_type_valid(type_left) && !saw_error) {
7706 "request for member '%Y' in something not a struct or union, but '%T'",
7710 return create_invalid_expression();
7713 assert(is_declaration(entry));
7714 select->select.compound_entry = entry;
7716 type_t *entry_type = entry->declaration.type;
7718 = get_qualified_type(entry_type, type_left->base.qualifiers);
7720 /* we always do the auto-type conversions; the & and sizeof parser contains
7721 * code to revert this! */
7722 select->base.type = automatic_type_conversion(res_type);
7724 type_t *skipped = skip_typeref(res_type);
7725 if (skipped->kind == TYPE_BITFIELD) {
7726 select->base.type = skipped->bitfield.base_type;
7732 static void check_call_argument(const function_parameter_t *parameter,
7733 call_argument_t *argument, unsigned pos)
7735 type_t *expected_type = parameter->type;
7736 type_t *expected_type_skip = skip_typeref(expected_type);
7737 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7738 expression_t *arg_expr = argument->expression;
7739 type_t *arg_type = skip_typeref(arg_expr->base.type);
7741 /* handle transparent union gnu extension */
7742 if (is_type_union(expected_type_skip)
7743 && (expected_type_skip->base.modifiers
7744 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7745 compound_t *union_decl = expected_type_skip->compound.compound;
7746 type_t *best_type = NULL;
7747 entity_t *entry = union_decl->members.entities;
7748 for ( ; entry != NULL; entry = entry->base.next) {
7749 assert(is_declaration(entry));
7750 type_t *decl_type = entry->declaration.type;
7751 error = semantic_assign(decl_type, arg_expr);
7752 if (error == ASSIGN_ERROR_INCOMPATIBLE
7753 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7756 if (error == ASSIGN_SUCCESS) {
7757 best_type = decl_type;
7758 } else if (best_type == NULL) {
7759 best_type = decl_type;
7763 if (best_type != NULL) {
7764 expected_type = best_type;
7768 error = semantic_assign(expected_type, arg_expr);
7769 argument->expression = create_implicit_cast(argument->expression,
7772 if (error != ASSIGN_SUCCESS) {
7773 /* report exact scope in error messages (like "in argument 3") */
7775 snprintf(buf, sizeof(buf), "call argument %u", pos);
7776 report_assign_error(error, expected_type, arg_expr, buf,
7777 &arg_expr->base.source_position);
7778 } else if (warning.traditional || warning.conversion) {
7779 type_t *const promoted_type = get_default_promoted_type(arg_type);
7780 if (!types_compatible(expected_type_skip, promoted_type) &&
7781 !types_compatible(expected_type_skip, type_void_ptr) &&
7782 !types_compatible(type_void_ptr, promoted_type)) {
7783 /* Deliberately show the skipped types in this warning */
7784 warningf(&arg_expr->base.source_position,
7785 "passing call argument %u as '%T' rather than '%T' due to prototype",
7786 pos, expected_type_skip, promoted_type);
7792 * Parse a call expression, ie. expression '( ... )'.
7794 * @param expression the function address
7796 static expression_t *parse_call_expression(expression_t *expression)
7798 expression_t *result = allocate_expression_zero(EXPR_CALL);
7799 call_expression_t *call = &result->call;
7800 call->function = expression;
7802 type_t *const orig_type = expression->base.type;
7803 type_t *const type = skip_typeref(orig_type);
7805 function_type_t *function_type = NULL;
7806 if (is_type_pointer(type)) {
7807 type_t *const to_type = skip_typeref(type->pointer.points_to);
7809 if (is_type_function(to_type)) {
7810 function_type = &to_type->function;
7811 call->base.type = function_type->return_type;
7815 if (function_type == NULL && is_type_valid(type)) {
7816 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7819 /* parse arguments */
7821 add_anchor_token(')');
7822 add_anchor_token(',');
7824 if (token.type != ')') {
7825 call_argument_t *last_argument = NULL;
7828 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7830 argument->expression = parse_assignment_expression();
7831 if (last_argument == NULL) {
7832 call->arguments = argument;
7834 last_argument->next = argument;
7836 last_argument = argument;
7838 if (token.type != ',')
7843 rem_anchor_token(',');
7844 rem_anchor_token(')');
7847 if (function_type == NULL)
7850 function_parameter_t *parameter = function_type->parameters;
7851 call_argument_t *argument = call->arguments;
7852 if (!function_type->unspecified_parameters) {
7853 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7854 parameter = parameter->next, argument = argument->next) {
7855 check_call_argument(parameter, argument, ++pos);
7858 if (parameter != NULL) {
7859 errorf(HERE, "too few arguments to function '%E'", expression);
7860 } else if (argument != NULL && !function_type->variadic) {
7861 errorf(HERE, "too many arguments to function '%E'", expression);
7865 /* do default promotion */
7866 for (; argument != NULL; argument = argument->next) {
7867 type_t *type = argument->expression->base.type;
7869 type = get_default_promoted_type(type);
7871 argument->expression
7872 = create_implicit_cast(argument->expression, type);
7875 check_format(&result->call);
7877 if (warning.aggregate_return &&
7878 is_type_compound(skip_typeref(function_type->return_type))) {
7879 warningf(&result->base.source_position,
7880 "function call has aggregate value");
7887 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7889 static bool same_compound_type(const type_t *type1, const type_t *type2)
7892 is_type_compound(type1) &&
7893 type1->kind == type2->kind &&
7894 type1->compound.compound == type2->compound.compound;
7897 static expression_t const *get_reference_address(expression_t const *expr)
7899 bool regular_take_address = true;
7901 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7902 expr = expr->unary.value;
7904 regular_take_address = false;
7907 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7910 expr = expr->unary.value;
7913 if (expr->kind != EXPR_REFERENCE)
7916 /* special case for functions which are automatically converted to a
7917 * pointer to function without an extra TAKE_ADDRESS operation */
7918 if (!regular_take_address &&
7919 expr->reference.entity->kind != ENTITY_FUNCTION) {
7926 static void warn_reference_address_as_bool(expression_t const* expr)
7928 if (!warning.address)
7931 expr = get_reference_address(expr);
7933 warningf(&expr->base.source_position,
7934 "the address of '%Y' will always evaluate as 'true'",
7935 expr->reference.entity->base.symbol);
7939 static void semantic_condition(expression_t const *const expr,
7940 char const *const context)
7942 type_t *const type = skip_typeref(expr->base.type);
7943 if (is_type_scalar(type)) {
7944 warn_reference_address_as_bool(expr);
7945 } else if (is_type_valid(type)) {
7946 errorf(&expr->base.source_position,
7947 "%s must have scalar type", context);
7952 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7954 * @param expression the conditional expression
7956 static expression_t *parse_conditional_expression(expression_t *expression)
7958 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7960 conditional_expression_t *conditional = &result->conditional;
7961 conditional->condition = expression;
7964 add_anchor_token(':');
7966 /* §6.5.15:2 The first operand shall have scalar type. */
7967 semantic_condition(expression, "condition of conditional operator");
7969 expression_t *true_expression = expression;
7970 bool gnu_cond = false;
7971 if (GNU_MODE && token.type == ':') {
7974 true_expression = parse_expression();
7976 rem_anchor_token(':');
7978 expression_t *false_expression =
7979 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7981 type_t *const orig_true_type = true_expression->base.type;
7982 type_t *const orig_false_type = false_expression->base.type;
7983 type_t *const true_type = skip_typeref(orig_true_type);
7984 type_t *const false_type = skip_typeref(orig_false_type);
7987 type_t *result_type;
7988 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7989 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7990 /* ISO/IEC 14882:1998(E) §5.16:2 */
7991 if (true_expression->kind == EXPR_UNARY_THROW) {
7992 result_type = false_type;
7993 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7994 result_type = true_type;
7996 if (warning.other && (
7997 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7998 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
8000 warningf(&conditional->base.source_position,
8001 "ISO C forbids conditional expression with only one void side");
8003 result_type = type_void;
8005 } else if (is_type_arithmetic(true_type)
8006 && is_type_arithmetic(false_type)) {
8007 result_type = semantic_arithmetic(true_type, false_type);
8009 true_expression = create_implicit_cast(true_expression, result_type);
8010 false_expression = create_implicit_cast(false_expression, result_type);
8012 conditional->true_expression = true_expression;
8013 conditional->false_expression = false_expression;
8014 conditional->base.type = result_type;
8015 } else if (same_compound_type(true_type, false_type)) {
8016 /* just take 1 of the 2 types */
8017 result_type = true_type;
8018 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
8019 type_t *pointer_type;
8021 expression_t *other_expression;
8022 if (is_type_pointer(true_type) &&
8023 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
8024 pointer_type = true_type;
8025 other_type = false_type;
8026 other_expression = false_expression;
8028 pointer_type = false_type;
8029 other_type = true_type;
8030 other_expression = true_expression;
8033 if (is_null_pointer_constant(other_expression)) {
8034 result_type = pointer_type;
8035 } else if (is_type_pointer(other_type)) {
8036 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
8037 type_t *to2 = skip_typeref(other_type->pointer.points_to);
8040 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
8041 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
8043 } else if (types_compatible(get_unqualified_type(to1),
8044 get_unqualified_type(to2))) {
8047 if (warning.other) {
8048 warningf(&conditional->base.source_position,
8049 "pointer types '%T' and '%T' in conditional expression are incompatible",
8050 true_type, false_type);
8055 type_t *const type =
8056 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
8057 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
8058 } else if (is_type_integer(other_type)) {
8059 if (warning.other) {
8060 warningf(&conditional->base.source_position,
8061 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
8063 result_type = pointer_type;
8065 if (is_type_valid(other_type)) {
8066 type_error_incompatible("while parsing conditional",
8067 &expression->base.source_position, true_type, false_type);
8069 result_type = type_error_type;
8072 if (is_type_valid(true_type) && is_type_valid(false_type)) {
8073 type_error_incompatible("while parsing conditional",
8074 &conditional->base.source_position, true_type,
8077 result_type = type_error_type;
8080 conditional->true_expression
8081 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
8082 conditional->false_expression
8083 = create_implicit_cast(false_expression, result_type);
8084 conditional->base.type = result_type;
8087 return create_invalid_expression();
8091 * Parse an extension expression.
8093 static expression_t *parse_extension(void)
8095 eat(T___extension__);
8097 bool old_gcc_extension = in_gcc_extension;
8098 in_gcc_extension = true;
8099 expression_t *expression = parse_sub_expression(PREC_UNARY);
8100 in_gcc_extension = old_gcc_extension;
8105 * Parse a __builtin_classify_type() expression.
8107 static expression_t *parse_builtin_classify_type(void)
8109 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
8110 result->base.type = type_int;
8112 eat(T___builtin_classify_type);
8115 add_anchor_token(')');
8116 expression_t *expression = parse_expression();
8117 rem_anchor_token(')');
8119 result->classify_type.type_expression = expression;
8123 return create_invalid_expression();
8127 * Parse a delete expression
8128 * ISO/IEC 14882:1998(E) §5.3.5
8130 static expression_t *parse_delete(void)
8132 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
8133 result->base.type = type_void;
8137 if (token.type == '[') {
8139 result->kind = EXPR_UNARY_DELETE_ARRAY;
8144 expression_t *const value = parse_sub_expression(PREC_CAST);
8145 result->unary.value = value;
8147 type_t *const type = skip_typeref(value->base.type);
8148 if (!is_type_pointer(type)) {
8149 errorf(&value->base.source_position,
8150 "operand of delete must have pointer type");
8151 } else if (warning.other &&
8152 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
8153 warningf(&value->base.source_position,
8154 "deleting 'void*' is undefined");
8161 * Parse a throw expression
8162 * ISO/IEC 14882:1998(E) §15:1
8164 static expression_t *parse_throw(void)
8166 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
8167 result->base.type = type_void;
8171 expression_t *value = NULL;
8172 switch (token.type) {
8174 value = parse_assignment_expression();
8175 /* ISO/IEC 14882:1998(E) §15.1:3 */
8176 type_t *const orig_type = value->base.type;
8177 type_t *const type = skip_typeref(orig_type);
8178 if (is_type_incomplete(type)) {
8179 errorf(&value->base.source_position,
8180 "cannot throw object of incomplete type '%T'", orig_type);
8181 } else if (is_type_pointer(type)) {
8182 type_t *const points_to = skip_typeref(type->pointer.points_to);
8183 if (is_type_incomplete(points_to) &&
8184 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8185 errorf(&value->base.source_position,
8186 "cannot throw pointer to incomplete type '%T'", orig_type);
8194 result->unary.value = value;
8199 static bool check_pointer_arithmetic(const source_position_t *source_position,
8200 type_t *pointer_type,
8201 type_t *orig_pointer_type)
8203 type_t *points_to = pointer_type->pointer.points_to;
8204 points_to = skip_typeref(points_to);
8206 if (is_type_incomplete(points_to)) {
8207 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8208 errorf(source_position,
8209 "arithmetic with pointer to incomplete type '%T' not allowed",
8212 } else if (warning.pointer_arith) {
8213 warningf(source_position,
8214 "pointer of type '%T' used in arithmetic",
8217 } else if (is_type_function(points_to)) {
8219 errorf(source_position,
8220 "arithmetic with pointer to function type '%T' not allowed",
8223 } else if (warning.pointer_arith) {
8224 warningf(source_position,
8225 "pointer to a function '%T' used in arithmetic",
8232 static bool is_lvalue(const expression_t *expression)
8234 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8235 switch (expression->kind) {
8236 case EXPR_REFERENCE:
8237 case EXPR_ARRAY_ACCESS:
8239 case EXPR_UNARY_DEREFERENCE:
8243 type_t *type = skip_typeref(expression->base.type);
8245 /* ISO/IEC 14882:1998(E) §3.10:3 */
8246 is_type_reference(type) ||
8247 /* Claim it is an lvalue, if the type is invalid. There was a parse
8248 * error before, which maybe prevented properly recognizing it as
8250 !is_type_valid(type);
8255 static void semantic_incdec(unary_expression_t *expression)
8257 type_t *const orig_type = expression->value->base.type;
8258 type_t *const type = skip_typeref(orig_type);
8259 if (is_type_pointer(type)) {
8260 if (!check_pointer_arithmetic(&expression->base.source_position,
8264 } else if (!is_type_real(type) && is_type_valid(type)) {
8265 /* TODO: improve error message */
8266 errorf(&expression->base.source_position,
8267 "operation needs an arithmetic or pointer type");
8270 if (!is_lvalue(expression->value)) {
8271 /* TODO: improve error message */
8272 errorf(&expression->base.source_position, "lvalue required as operand");
8274 expression->base.type = orig_type;
8277 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8279 type_t *const orig_type = expression->value->base.type;
8280 type_t *const type = skip_typeref(orig_type);
8281 if (!is_type_arithmetic(type)) {
8282 if (is_type_valid(type)) {
8283 /* TODO: improve error message */
8284 errorf(&expression->base.source_position,
8285 "operation needs an arithmetic type");
8290 expression->base.type = orig_type;
8293 static void semantic_unexpr_plus(unary_expression_t *expression)
8295 semantic_unexpr_arithmetic(expression);
8296 if (warning.traditional)
8297 warningf(&expression->base.source_position,
8298 "traditional C rejects the unary plus operator");
8301 static void semantic_not(unary_expression_t *expression)
8303 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8304 semantic_condition(expression->value, "operand of !");
8305 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8308 static void semantic_unexpr_integer(unary_expression_t *expression)
8310 type_t *const orig_type = expression->value->base.type;
8311 type_t *const type = skip_typeref(orig_type);
8312 if (!is_type_integer(type)) {
8313 if (is_type_valid(type)) {
8314 errorf(&expression->base.source_position,
8315 "operand of ~ must be of integer type");
8320 expression->base.type = orig_type;
8323 static void semantic_dereference(unary_expression_t *expression)
8325 type_t *const orig_type = expression->value->base.type;
8326 type_t *const type = skip_typeref(orig_type);
8327 if (!is_type_pointer(type)) {
8328 if (is_type_valid(type)) {
8329 errorf(&expression->base.source_position,
8330 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8335 type_t *result_type = type->pointer.points_to;
8336 result_type = automatic_type_conversion(result_type);
8337 expression->base.type = result_type;
8341 * Record that an address is taken (expression represents an lvalue).
8343 * @param expression the expression
8344 * @param may_be_register if true, the expression might be an register
8346 static void set_address_taken(expression_t *expression, bool may_be_register)
8348 if (expression->kind != EXPR_REFERENCE)
8351 entity_t *const entity = expression->reference.entity;
8353 if (entity->kind != ENTITY_VARIABLE)
8356 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8357 && !may_be_register) {
8358 errorf(&expression->base.source_position,
8359 "address of register variable '%Y' requested",
8360 entity->base.symbol);
8363 entity->variable.address_taken = true;
8367 * Check the semantic of the address taken expression.
8369 static void semantic_take_addr(unary_expression_t *expression)
8371 expression_t *value = expression->value;
8372 value->base.type = revert_automatic_type_conversion(value);
8374 type_t *orig_type = value->base.type;
8375 type_t *type = skip_typeref(orig_type);
8376 if (!is_type_valid(type))
8380 if (!is_lvalue(value)) {
8381 errorf(&expression->base.source_position, "'&' requires an lvalue");
8383 if (type->kind == TYPE_BITFIELD) {
8384 errorf(&expression->base.source_position,
8385 "'&' not allowed on object with bitfield type '%T'",
8389 set_address_taken(value, false);
8391 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8394 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8395 static expression_t *parse_##unexpression_type(void) \
8397 expression_t *unary_expression \
8398 = allocate_expression_zero(unexpression_type); \
8400 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8402 sfunc(&unary_expression->unary); \
8404 return unary_expression; \
8407 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8408 semantic_unexpr_arithmetic)
8409 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8410 semantic_unexpr_plus)
8411 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8413 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8414 semantic_dereference)
8415 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8417 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8418 semantic_unexpr_integer)
8419 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8421 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8424 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8426 static expression_t *parse_##unexpression_type(expression_t *left) \
8428 expression_t *unary_expression \
8429 = allocate_expression_zero(unexpression_type); \
8431 unary_expression->unary.value = left; \
8433 sfunc(&unary_expression->unary); \
8435 return unary_expression; \
8438 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8439 EXPR_UNARY_POSTFIX_INCREMENT,
8441 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8442 EXPR_UNARY_POSTFIX_DECREMENT,
8445 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8447 /* TODO: handle complex + imaginary types */
8449 type_left = get_unqualified_type(type_left);
8450 type_right = get_unqualified_type(type_right);
8452 /* § 6.3.1.8 Usual arithmetic conversions */
8453 if (type_left == type_long_double || type_right == type_long_double) {
8454 return type_long_double;
8455 } else if (type_left == type_double || type_right == type_double) {
8457 } else if (type_left == type_float || type_right == type_float) {
8461 type_left = promote_integer(type_left);
8462 type_right = promote_integer(type_right);
8464 if (type_left == type_right)
8467 bool const signed_left = is_type_signed(type_left);
8468 bool const signed_right = is_type_signed(type_right);
8469 int const rank_left = get_rank(type_left);
8470 int const rank_right = get_rank(type_right);
8472 if (signed_left == signed_right)
8473 return rank_left >= rank_right ? type_left : type_right;
8482 u_rank = rank_right;
8483 u_type = type_right;
8485 s_rank = rank_right;
8486 s_type = type_right;
8491 if (u_rank >= s_rank)
8494 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8496 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8497 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8501 case ATOMIC_TYPE_INT: return type_unsigned_int;
8502 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8503 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8505 default: panic("invalid atomic type");
8510 * Check the semantic restrictions for a binary expression.
8512 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8514 expression_t *const left = expression->left;
8515 expression_t *const right = expression->right;
8516 type_t *const orig_type_left = left->base.type;
8517 type_t *const orig_type_right = right->base.type;
8518 type_t *const type_left = skip_typeref(orig_type_left);
8519 type_t *const type_right = skip_typeref(orig_type_right);
8521 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8522 /* TODO: improve error message */
8523 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8524 errorf(&expression->base.source_position,
8525 "operation needs arithmetic types");
8530 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8531 expression->left = create_implicit_cast(left, arithmetic_type);
8532 expression->right = create_implicit_cast(right, arithmetic_type);
8533 expression->base.type = arithmetic_type;
8536 static void warn_div_by_zero(binary_expression_t const *const expression)
8538 if (!warning.div_by_zero ||
8539 !is_type_integer(expression->base.type))
8542 expression_t const *const right = expression->right;
8543 /* The type of the right operand can be different for /= */
8544 if (is_type_integer(right->base.type) &&
8545 is_constant_expression(right) &&
8546 fold_constant(right) == 0) {
8547 warningf(&expression->base.source_position, "division by zero");
8552 * Check the semantic restrictions for a div/mod expression.
8554 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8555 semantic_binexpr_arithmetic(expression);
8556 warn_div_by_zero(expression);
8559 static void semantic_shift_op(binary_expression_t *expression)
8561 expression_t *const left = expression->left;
8562 expression_t *const right = expression->right;
8563 type_t *const orig_type_left = left->base.type;
8564 type_t *const orig_type_right = right->base.type;
8565 type_t * type_left = skip_typeref(orig_type_left);
8566 type_t * type_right = skip_typeref(orig_type_right);
8568 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8569 /* TODO: improve error message */
8570 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8571 errorf(&expression->base.source_position,
8572 "operands of shift operation must have integer types");
8577 type_left = promote_integer(type_left);
8578 type_right = promote_integer(type_right);
8580 expression->left = create_implicit_cast(left, type_left);
8581 expression->right = create_implicit_cast(right, type_right);
8582 expression->base.type = type_left;
8585 static void semantic_add(binary_expression_t *expression)
8587 expression_t *const left = expression->left;
8588 expression_t *const right = expression->right;
8589 type_t *const orig_type_left = left->base.type;
8590 type_t *const orig_type_right = right->base.type;
8591 type_t *const type_left = skip_typeref(orig_type_left);
8592 type_t *const type_right = skip_typeref(orig_type_right);
8595 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8596 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8597 expression->left = create_implicit_cast(left, arithmetic_type);
8598 expression->right = create_implicit_cast(right, arithmetic_type);
8599 expression->base.type = arithmetic_type;
8601 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8602 check_pointer_arithmetic(&expression->base.source_position,
8603 type_left, orig_type_left);
8604 expression->base.type = type_left;
8605 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8606 check_pointer_arithmetic(&expression->base.source_position,
8607 type_right, orig_type_right);
8608 expression->base.type = type_right;
8609 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8610 errorf(&expression->base.source_position,
8611 "invalid operands to binary + ('%T', '%T')",
8612 orig_type_left, orig_type_right);
8616 static void semantic_sub(binary_expression_t *expression)
8618 expression_t *const left = expression->left;
8619 expression_t *const right = expression->right;
8620 type_t *const orig_type_left = left->base.type;
8621 type_t *const orig_type_right = right->base.type;
8622 type_t *const type_left = skip_typeref(orig_type_left);
8623 type_t *const type_right = skip_typeref(orig_type_right);
8624 source_position_t const *const pos = &expression->base.source_position;
8627 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8628 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8629 expression->left = create_implicit_cast(left, arithmetic_type);
8630 expression->right = create_implicit_cast(right, arithmetic_type);
8631 expression->base.type = arithmetic_type;
8633 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8634 check_pointer_arithmetic(&expression->base.source_position,
8635 type_left, orig_type_left);
8636 expression->base.type = type_left;
8637 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8638 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8639 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8640 if (!types_compatible(unqual_left, unqual_right)) {
8642 "subtracting pointers to incompatible types '%T' and '%T'",
8643 orig_type_left, orig_type_right);
8644 } else if (!is_type_object(unqual_left)) {
8645 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8646 errorf(pos, "subtracting pointers to non-object types '%T'",
8648 } else if (warning.other) {
8649 warningf(pos, "subtracting pointers to void");
8652 expression->base.type = type_ptrdiff_t;
8653 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8654 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8655 orig_type_left, orig_type_right);
8659 static void warn_string_literal_address(expression_t const* expr)
8661 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8662 expr = expr->unary.value;
8663 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8665 expr = expr->unary.value;
8668 if (expr->kind == EXPR_STRING_LITERAL ||
8669 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8670 warningf(&expr->base.source_position,
8671 "comparison with string literal results in unspecified behaviour");
8676 * Check the semantics of comparison expressions.
8678 * @param expression The expression to check.
8680 static void semantic_comparison(binary_expression_t *expression)
8682 expression_t *left = expression->left;
8683 expression_t *right = expression->right;
8685 if (warning.address) {
8686 warn_string_literal_address(left);
8687 warn_string_literal_address(right);
8689 expression_t const* const func_left = get_reference_address(left);
8690 if (func_left != NULL && is_null_pointer_constant(right)) {
8691 warningf(&expression->base.source_position,
8692 "the address of '%Y' will never be NULL",
8693 func_left->reference.entity->base.symbol);
8696 expression_t const* const func_right = get_reference_address(right);
8697 if (func_right != NULL && is_null_pointer_constant(right)) {
8698 warningf(&expression->base.source_position,
8699 "the address of '%Y' will never be NULL",
8700 func_right->reference.entity->base.symbol);
8704 type_t *orig_type_left = left->base.type;
8705 type_t *orig_type_right = right->base.type;
8706 type_t *type_left = skip_typeref(orig_type_left);
8707 type_t *type_right = skip_typeref(orig_type_right);
8709 /* TODO non-arithmetic types */
8710 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8711 /* test for signed vs unsigned compares */
8712 if (warning.sign_compare &&
8713 (expression->base.kind != EXPR_BINARY_EQUAL &&
8714 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8715 (is_type_signed(type_left) != is_type_signed(type_right))) {
8717 /* check if 1 of the operands is a constant, in this case we just
8718 * check wether we can safely represent the resulting constant in
8719 * the type of the other operand. */
8720 expression_t *const_expr = NULL;
8721 expression_t *other_expr = NULL;
8723 if (is_constant_expression(left)) {
8726 } else if (is_constant_expression(right)) {
8731 if (const_expr != NULL) {
8732 type_t *other_type = skip_typeref(other_expr->base.type);
8733 long val = fold_constant(const_expr);
8734 /* TODO: check if val can be represented by other_type */
8738 warningf(&expression->base.source_position,
8739 "comparison between signed and unsigned");
8741 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8742 expression->left = create_implicit_cast(left, arithmetic_type);
8743 expression->right = create_implicit_cast(right, arithmetic_type);
8744 expression->base.type = arithmetic_type;
8745 if (warning.float_equal &&
8746 (expression->base.kind == EXPR_BINARY_EQUAL ||
8747 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8748 is_type_float(arithmetic_type)) {
8749 warningf(&expression->base.source_position,
8750 "comparing floating point with == or != is unsafe");
8752 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8753 /* TODO check compatibility */
8754 } else if (is_type_pointer(type_left)) {
8755 expression->right = create_implicit_cast(right, type_left);
8756 } else if (is_type_pointer(type_right)) {
8757 expression->left = create_implicit_cast(left, type_right);
8758 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8759 type_error_incompatible("invalid operands in comparison",
8760 &expression->base.source_position,
8761 type_left, type_right);
8763 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8767 * Checks if a compound type has constant fields.
8769 static bool has_const_fields(const compound_type_t *type)
8771 compound_t *compound = type->compound;
8772 entity_t *entry = compound->members.entities;
8774 for (; entry != NULL; entry = entry->base.next) {
8775 if (!is_declaration(entry))
8778 const type_t *decl_type = skip_typeref(entry->declaration.type);
8779 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8786 static bool is_valid_assignment_lhs(expression_t const* const left)
8788 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8789 type_t *const type_left = skip_typeref(orig_type_left);
8791 if (!is_lvalue(left)) {
8792 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8797 if (is_type_array(type_left)) {
8798 errorf(HERE, "cannot assign to arrays ('%E')", left);
8801 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8802 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8806 if (is_type_incomplete(type_left)) {
8807 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8808 left, orig_type_left);
8811 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8812 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8813 left, orig_type_left);
8820 static void semantic_arithmetic_assign(binary_expression_t *expression)
8822 expression_t *left = expression->left;
8823 expression_t *right = expression->right;
8824 type_t *orig_type_left = left->base.type;
8825 type_t *orig_type_right = right->base.type;
8827 if (!is_valid_assignment_lhs(left))
8830 type_t *type_left = skip_typeref(orig_type_left);
8831 type_t *type_right = skip_typeref(orig_type_right);
8833 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8834 /* TODO: improve error message */
8835 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8836 errorf(&expression->base.source_position,
8837 "operation needs arithmetic types");
8842 /* combined instructions are tricky. We can't create an implicit cast on
8843 * the left side, because we need the uncasted form for the store.
8844 * The ast2firm pass has to know that left_type must be right_type
8845 * for the arithmetic operation and create a cast by itself */
8846 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8847 expression->right = create_implicit_cast(right, arithmetic_type);
8848 expression->base.type = type_left;
8851 static void semantic_divmod_assign(binary_expression_t *expression)
8853 semantic_arithmetic_assign(expression);
8854 warn_div_by_zero(expression);
8857 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8859 expression_t *const left = expression->left;
8860 expression_t *const right = expression->right;
8861 type_t *const orig_type_left = left->base.type;
8862 type_t *const orig_type_right = right->base.type;
8863 type_t *const type_left = skip_typeref(orig_type_left);
8864 type_t *const type_right = skip_typeref(orig_type_right);
8866 if (!is_valid_assignment_lhs(left))
8869 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8870 /* combined instructions are tricky. We can't create an implicit cast on
8871 * the left side, because we need the uncasted form for the store.
8872 * The ast2firm pass has to know that left_type must be right_type
8873 * for the arithmetic operation and create a cast by itself */
8874 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8875 expression->right = create_implicit_cast(right, arithmetic_type);
8876 expression->base.type = type_left;
8877 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8878 check_pointer_arithmetic(&expression->base.source_position,
8879 type_left, orig_type_left);
8880 expression->base.type = type_left;
8881 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8882 errorf(&expression->base.source_position,
8883 "incompatible types '%T' and '%T' in assignment",
8884 orig_type_left, orig_type_right);
8889 * Check the semantic restrictions of a logical expression.
8891 static void semantic_logical_op(binary_expression_t *expression)
8893 /* §6.5.13:2 Each of the operands shall have scalar type.
8894 * §6.5.14:2 Each of the operands shall have scalar type. */
8895 semantic_condition(expression->left, "left operand of logical operator");
8896 semantic_condition(expression->right, "right operand of logical operator");
8897 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8901 * Check the semantic restrictions of a binary assign expression.
8903 static void semantic_binexpr_assign(binary_expression_t *expression)
8905 expression_t *left = expression->left;
8906 type_t *orig_type_left = left->base.type;
8908 if (!is_valid_assignment_lhs(left))
8911 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8912 report_assign_error(error, orig_type_left, expression->right,
8913 "assignment", &left->base.source_position);
8914 expression->right = create_implicit_cast(expression->right, orig_type_left);
8915 expression->base.type = orig_type_left;
8919 * Determine if the outermost operation (or parts thereof) of the given
8920 * expression has no effect in order to generate a warning about this fact.
8921 * Therefore in some cases this only examines some of the operands of the
8922 * expression (see comments in the function and examples below).
8924 * f() + 23; // warning, because + has no effect
8925 * x || f(); // no warning, because x controls execution of f()
8926 * x ? y : f(); // warning, because y has no effect
8927 * (void)x; // no warning to be able to suppress the warning
8928 * This function can NOT be used for an "expression has definitely no effect"-
8930 static bool expression_has_effect(const expression_t *const expr)
8932 switch (expr->kind) {
8933 case EXPR_UNKNOWN: break;
8934 case EXPR_INVALID: return true; /* do NOT warn */
8935 case EXPR_REFERENCE: return false;
8936 case EXPR_REFERENCE_ENUM_VALUE: return false;
8937 /* suppress the warning for microsoft __noop operations */
8938 case EXPR_CONST: return expr->conste.is_ms_noop;
8939 case EXPR_CHARACTER_CONSTANT: return false;
8940 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8941 case EXPR_STRING_LITERAL: return false;
8942 case EXPR_WIDE_STRING_LITERAL: return false;
8943 case EXPR_LABEL_ADDRESS: return false;
8946 const call_expression_t *const call = &expr->call;
8947 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8950 switch (call->function->builtin_symbol.symbol->ID) {
8951 case T___builtin_va_end: return true;
8952 default: return false;
8956 /* Generate the warning if either the left or right hand side of a
8957 * conditional expression has no effect */
8958 case EXPR_CONDITIONAL: {
8959 const conditional_expression_t *const cond = &expr->conditional;
8961 expression_has_effect(cond->true_expression) &&
8962 expression_has_effect(cond->false_expression);
8965 case EXPR_SELECT: return false;
8966 case EXPR_ARRAY_ACCESS: return false;
8967 case EXPR_SIZEOF: return false;
8968 case EXPR_CLASSIFY_TYPE: return false;
8969 case EXPR_ALIGNOF: return false;
8971 case EXPR_FUNCNAME: return false;
8972 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8973 case EXPR_BUILTIN_CONSTANT_P: return false;
8974 case EXPR_BUILTIN_PREFETCH: return true;
8975 case EXPR_OFFSETOF: return false;
8976 case EXPR_VA_START: return true;
8977 case EXPR_VA_ARG: return true;
8978 case EXPR_STATEMENT: return true; // TODO
8979 case EXPR_COMPOUND_LITERAL: return false;
8981 case EXPR_UNARY_NEGATE: return false;
8982 case EXPR_UNARY_PLUS: return false;
8983 case EXPR_UNARY_BITWISE_NEGATE: return false;
8984 case EXPR_UNARY_NOT: return false;
8985 case EXPR_UNARY_DEREFERENCE: return false;
8986 case EXPR_UNARY_TAKE_ADDRESS: return false;
8987 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8988 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8989 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8990 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8992 /* Treat void casts as if they have an effect in order to being able to
8993 * suppress the warning */
8994 case EXPR_UNARY_CAST: {
8995 type_t *const type = skip_typeref(expr->base.type);
8996 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8999 case EXPR_UNARY_CAST_IMPLICIT: return true;
9000 case EXPR_UNARY_ASSUME: return true;
9001 case EXPR_UNARY_DELETE: return true;
9002 case EXPR_UNARY_DELETE_ARRAY: return true;
9003 case EXPR_UNARY_THROW: return true;
9005 case EXPR_BINARY_ADD: return false;
9006 case EXPR_BINARY_SUB: return false;
9007 case EXPR_BINARY_MUL: return false;
9008 case EXPR_BINARY_DIV: return false;
9009 case EXPR_BINARY_MOD: return false;
9010 case EXPR_BINARY_EQUAL: return false;
9011 case EXPR_BINARY_NOTEQUAL: return false;
9012 case EXPR_BINARY_LESS: return false;
9013 case EXPR_BINARY_LESSEQUAL: return false;
9014 case EXPR_BINARY_GREATER: return false;
9015 case EXPR_BINARY_GREATEREQUAL: return false;
9016 case EXPR_BINARY_BITWISE_AND: return false;
9017 case EXPR_BINARY_BITWISE_OR: return false;
9018 case EXPR_BINARY_BITWISE_XOR: return false;
9019 case EXPR_BINARY_SHIFTLEFT: return false;
9020 case EXPR_BINARY_SHIFTRIGHT: return false;
9021 case EXPR_BINARY_ASSIGN: return true;
9022 case EXPR_BINARY_MUL_ASSIGN: return true;
9023 case EXPR_BINARY_DIV_ASSIGN: return true;
9024 case EXPR_BINARY_MOD_ASSIGN: return true;
9025 case EXPR_BINARY_ADD_ASSIGN: return true;
9026 case EXPR_BINARY_SUB_ASSIGN: return true;
9027 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
9028 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
9029 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
9030 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
9031 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
9033 /* Only examine the right hand side of && and ||, because the left hand
9034 * side already has the effect of controlling the execution of the right
9036 case EXPR_BINARY_LOGICAL_AND:
9037 case EXPR_BINARY_LOGICAL_OR:
9038 /* Only examine the right hand side of a comma expression, because the left
9039 * hand side has a separate warning */
9040 case EXPR_BINARY_COMMA:
9041 return expression_has_effect(expr->binary.right);
9043 case EXPR_BINARY_BUILTIN_EXPECT: return true;
9044 case EXPR_BINARY_ISGREATER: return false;
9045 case EXPR_BINARY_ISGREATEREQUAL: return false;
9046 case EXPR_BINARY_ISLESS: return false;
9047 case EXPR_BINARY_ISLESSEQUAL: return false;
9048 case EXPR_BINARY_ISLESSGREATER: return false;
9049 case EXPR_BINARY_ISUNORDERED: return false;
9052 internal_errorf(HERE, "unexpected expression");
9055 static void semantic_comma(binary_expression_t *expression)
9057 if (warning.unused_value) {
9058 const expression_t *const left = expression->left;
9059 if (!expression_has_effect(left)) {
9060 warningf(&left->base.source_position,
9061 "left-hand operand of comma expression has no effect");
9064 expression->base.type = expression->right->base.type;
9068 * @param prec_r precedence of the right operand
9070 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9071 static expression_t *parse_##binexpression_type(expression_t *left) \
9073 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9074 binexpr->binary.left = left; \
9077 expression_t *right = parse_sub_expression(prec_r); \
9079 binexpr->binary.right = right; \
9080 sfunc(&binexpr->binary); \
9085 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9086 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9087 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9088 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9089 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9090 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9091 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9092 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9093 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9094 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9095 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9096 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9097 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9098 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9099 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9100 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9101 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9102 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9103 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9104 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9105 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9106 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9107 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9108 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9109 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9110 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9111 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9112 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9113 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9114 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9117 static expression_t *parse_sub_expression(precedence_t precedence)
9119 if (token.type < 0) {
9120 return expected_expression_error();
9123 expression_parser_function_t *parser
9124 = &expression_parsers[token.type];
9125 source_position_t source_position = token.source_position;
9128 if (parser->parser != NULL) {
9129 left = parser->parser();
9131 left = parse_primary_expression();
9133 assert(left != NULL);
9134 left->base.source_position = source_position;
9137 if (token.type < 0) {
9138 return expected_expression_error();
9141 parser = &expression_parsers[token.type];
9142 if (parser->infix_parser == NULL)
9144 if (parser->infix_precedence < precedence)
9147 left = parser->infix_parser(left);
9149 assert(left != NULL);
9150 assert(left->kind != EXPR_UNKNOWN);
9151 left->base.source_position = source_position;
9158 * Parse an expression.
9160 static expression_t *parse_expression(void)
9162 return parse_sub_expression(PREC_EXPRESSION);
9166 * Register a parser for a prefix-like operator.
9168 * @param parser the parser function
9169 * @param token_type the token type of the prefix token
9171 static void register_expression_parser(parse_expression_function parser,
9174 expression_parser_function_t *entry = &expression_parsers[token_type];
9176 if (entry->parser != NULL) {
9177 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9178 panic("trying to register multiple expression parsers for a token");
9180 entry->parser = parser;
9184 * Register a parser for an infix operator with given precedence.
9186 * @param parser the parser function
9187 * @param token_type the token type of the infix operator
9188 * @param precedence the precedence of the operator
9190 static void register_infix_parser(parse_expression_infix_function parser,
9191 int token_type, unsigned precedence)
9193 expression_parser_function_t *entry = &expression_parsers[token_type];
9195 if (entry->infix_parser != NULL) {
9196 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9197 panic("trying to register multiple infix expression parsers for a "
9200 entry->infix_parser = parser;
9201 entry->infix_precedence = precedence;
9205 * Initialize the expression parsers.
9207 static void init_expression_parsers(void)
9209 memset(&expression_parsers, 0, sizeof(expression_parsers));
9211 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9212 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9213 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9214 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9215 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9216 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9217 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9218 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9219 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9220 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9221 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9222 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9223 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9224 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9225 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9226 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9227 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9228 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9229 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9230 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9231 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9232 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9233 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9234 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9235 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9236 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9237 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9238 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9239 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9240 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9241 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9242 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9243 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9244 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9245 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9246 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9247 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9249 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9250 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9251 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9252 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9253 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9254 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9255 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9256 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9257 register_expression_parser(parse_sizeof, T_sizeof);
9258 register_expression_parser(parse_alignof, T___alignof__);
9259 register_expression_parser(parse_extension, T___extension__);
9260 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9261 register_expression_parser(parse_delete, T_delete);
9262 register_expression_parser(parse_throw, T_throw);
9266 * Parse a asm statement arguments specification.
9268 static asm_argument_t *parse_asm_arguments(bool is_out)
9270 asm_argument_t *result = NULL;
9271 asm_argument_t **anchor = &result;
9273 while (token.type == T_STRING_LITERAL || token.type == '[') {
9274 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9275 memset(argument, 0, sizeof(argument[0]));
9277 if (token.type == '[') {
9279 if (token.type != T_IDENTIFIER) {
9280 parse_error_expected("while parsing asm argument",
9281 T_IDENTIFIER, NULL);
9284 argument->symbol = token.v.symbol;
9289 argument->constraints = parse_string_literals();
9291 add_anchor_token(')');
9292 expression_t *expression = parse_expression();
9293 rem_anchor_token(')');
9295 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9296 * change size or type representation (e.g. int -> long is ok, but
9297 * int -> float is not) */
9298 if (expression->kind == EXPR_UNARY_CAST) {
9299 type_t *const type = expression->base.type;
9300 type_kind_t const kind = type->kind;
9301 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9304 if (kind == TYPE_ATOMIC) {
9305 atomic_type_kind_t const akind = type->atomic.akind;
9306 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9307 size = get_atomic_type_size(akind);
9309 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9310 size = get_atomic_type_size(get_intptr_kind());
9314 expression_t *const value = expression->unary.value;
9315 type_t *const value_type = value->base.type;
9316 type_kind_t const value_kind = value_type->kind;
9318 unsigned value_flags;
9319 unsigned value_size;
9320 if (value_kind == TYPE_ATOMIC) {
9321 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9322 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9323 value_size = get_atomic_type_size(value_akind);
9324 } else if (value_kind == TYPE_POINTER) {
9325 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9326 value_size = get_atomic_type_size(get_intptr_kind());
9331 if (value_flags != flags || value_size != size)
9335 } while (expression->kind == EXPR_UNARY_CAST);
9339 if (!is_lvalue(expression)) {
9340 errorf(&expression->base.source_position,
9341 "asm output argument is not an lvalue");
9344 if (argument->constraints.begin[0] == '+')
9345 mark_vars_read(expression, NULL);
9347 mark_vars_read(expression, NULL);
9349 argument->expression = expression;
9352 set_address_taken(expression, true);
9355 anchor = &argument->next;
9357 if (token.type != ',')
9368 * Parse a asm statement clobber specification.
9370 static asm_clobber_t *parse_asm_clobbers(void)
9372 asm_clobber_t *result = NULL;
9373 asm_clobber_t *last = NULL;
9375 while (token.type == T_STRING_LITERAL) {
9376 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9377 clobber->clobber = parse_string_literals();
9380 last->next = clobber;
9386 if (token.type != ',')
9395 * Parse an asm statement.
9397 static statement_t *parse_asm_statement(void)
9399 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9400 asm_statement_t *asm_statement = &statement->asms;
9404 if (token.type == T_volatile) {
9406 asm_statement->is_volatile = true;
9410 add_anchor_token(')');
9411 add_anchor_token(':');
9412 asm_statement->asm_text = parse_string_literals();
9414 if (token.type != ':') {
9415 rem_anchor_token(':');
9420 asm_statement->outputs = parse_asm_arguments(true);
9421 if (token.type != ':') {
9422 rem_anchor_token(':');
9427 asm_statement->inputs = parse_asm_arguments(false);
9428 if (token.type != ':') {
9429 rem_anchor_token(':');
9432 rem_anchor_token(':');
9435 asm_statement->clobbers = parse_asm_clobbers();
9438 rem_anchor_token(')');
9442 if (asm_statement->outputs == NULL) {
9443 /* GCC: An 'asm' instruction without any output operands will be treated
9444 * identically to a volatile 'asm' instruction. */
9445 asm_statement->is_volatile = true;
9450 return create_invalid_statement();
9454 * Parse a case statement.
9456 static statement_t *parse_case_statement(void)
9458 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9459 source_position_t *const pos = &statement->base.source_position;
9463 expression_t *const expression = parse_expression();
9464 statement->case_label.expression = expression;
9465 if (!is_constant_expression(expression)) {
9466 /* This check does not prevent the error message in all cases of an
9467 * prior error while parsing the expression. At least it catches the
9468 * common case of a mistyped enum entry. */
9469 if (is_type_valid(skip_typeref(expression->base.type))) {
9470 errorf(pos, "case label does not reduce to an integer constant");
9472 statement->case_label.is_bad = true;
9474 long const val = fold_constant(expression);
9475 statement->case_label.first_case = val;
9476 statement->case_label.last_case = val;
9480 if (token.type == T_DOTDOTDOT) {
9482 expression_t *const end_range = parse_expression();
9483 statement->case_label.end_range = end_range;
9484 if (!is_constant_expression(end_range)) {
9485 /* This check does not prevent the error message in all cases of an
9486 * prior error while parsing the expression. At least it catches the
9487 * common case of a mistyped enum entry. */
9488 if (is_type_valid(skip_typeref(end_range->base.type))) {
9489 errorf(pos, "case range does not reduce to an integer constant");
9491 statement->case_label.is_bad = true;
9493 long const val = fold_constant(end_range);
9494 statement->case_label.last_case = val;
9496 if (warning.other && val < statement->case_label.first_case) {
9497 statement->case_label.is_empty_range = true;
9498 warningf(pos, "empty range specified");
9504 PUSH_PARENT(statement);
9508 if (current_switch != NULL) {
9509 if (! statement->case_label.is_bad) {
9510 /* Check for duplicate case values */
9511 case_label_statement_t *c = &statement->case_label;
9512 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9513 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9516 if (c->last_case < l->first_case || c->first_case > l->last_case)
9519 errorf(pos, "duplicate case value (previously used %P)",
9520 &l->base.source_position);
9524 /* link all cases into the switch statement */
9525 if (current_switch->last_case == NULL) {
9526 current_switch->first_case = &statement->case_label;
9528 current_switch->last_case->next = &statement->case_label;
9530 current_switch->last_case = &statement->case_label;
9532 errorf(pos, "case label not within a switch statement");
9535 statement_t *const inner_stmt = parse_statement();
9536 statement->case_label.statement = inner_stmt;
9537 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9538 errorf(&inner_stmt->base.source_position, "declaration after case label");
9545 return create_invalid_statement();
9549 * Parse a default statement.
9551 static statement_t *parse_default_statement(void)
9553 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9557 PUSH_PARENT(statement);
9560 if (current_switch != NULL) {
9561 const case_label_statement_t *def_label = current_switch->default_label;
9562 if (def_label != NULL) {
9563 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9564 &def_label->base.source_position);
9566 current_switch->default_label = &statement->case_label;
9568 /* link all cases into the switch statement */
9569 if (current_switch->last_case == NULL) {
9570 current_switch->first_case = &statement->case_label;
9572 current_switch->last_case->next = &statement->case_label;
9574 current_switch->last_case = &statement->case_label;
9577 errorf(&statement->base.source_position,
9578 "'default' label not within a switch statement");
9581 statement_t *const inner_stmt = parse_statement();
9582 statement->case_label.statement = inner_stmt;
9583 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9584 errorf(&inner_stmt->base.source_position, "declaration after default label");
9591 return create_invalid_statement();
9595 * Parse a label statement.
9597 static statement_t *parse_label_statement(void)
9599 assert(token.type == T_IDENTIFIER);
9600 symbol_t *symbol = token.v.symbol;
9601 label_t *label = get_label(symbol);
9603 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9604 statement->label.label = label;
9608 PUSH_PARENT(statement);
9610 /* if statement is already set then the label is defined twice,
9611 * otherwise it was just mentioned in a goto/local label declaration so far
9613 if (label->statement != NULL) {
9614 errorf(HERE, "duplicate label '%Y' (declared %P)",
9615 symbol, &label->base.source_position);
9617 label->base.source_position = token.source_position;
9618 label->statement = statement;
9623 if (token.type == '}') {
9624 /* TODO only warn? */
9625 if (warning.other && false) {
9626 warningf(HERE, "label at end of compound statement");
9627 statement->label.statement = create_empty_statement();
9629 errorf(HERE, "label at end of compound statement");
9630 statement->label.statement = create_invalid_statement();
9632 } else if (token.type == ';') {
9633 /* Eat an empty statement here, to avoid the warning about an empty
9634 * statement after a label. label:; is commonly used to have a label
9635 * before a closing brace. */
9636 statement->label.statement = create_empty_statement();
9639 statement_t *const inner_stmt = parse_statement();
9640 statement->label.statement = inner_stmt;
9641 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9642 errorf(&inner_stmt->base.source_position, "declaration after label");
9646 /* remember the labels in a list for later checking */
9647 *label_anchor = &statement->label;
9648 label_anchor = &statement->label.next;
9655 * Parse an if statement.
9657 static statement_t *parse_if(void)
9659 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9663 PUSH_PARENT(statement);
9665 add_anchor_token('{');
9668 add_anchor_token(')');
9669 expression_t *const expr = parse_expression();
9670 statement->ifs.condition = expr;
9671 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9673 semantic_condition(expr, "condition of 'if'-statment");
9674 mark_vars_read(expr, NULL);
9675 rem_anchor_token(')');
9679 rem_anchor_token('{');
9681 add_anchor_token(T_else);
9682 statement->ifs.true_statement = parse_statement();
9683 rem_anchor_token(T_else);
9685 if (token.type == T_else) {
9687 statement->ifs.false_statement = parse_statement();
9695 * Check that all enums are handled in a switch.
9697 * @param statement the switch statement to check
9699 static void check_enum_cases(const switch_statement_t *statement) {
9700 const type_t *type = skip_typeref(statement->expression->base.type);
9701 if (! is_type_enum(type))
9703 const enum_type_t *enumt = &type->enumt;
9705 /* if we have a default, no warnings */
9706 if (statement->default_label != NULL)
9709 /* FIXME: calculation of value should be done while parsing */
9710 /* TODO: quadratic algorithm here. Change to an n log n one */
9711 long last_value = -1;
9712 const entity_t *entry = enumt->enume->base.next;
9713 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9714 entry = entry->base.next) {
9715 const expression_t *expression = entry->enum_value.value;
9716 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9718 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9719 if (l->expression == NULL)
9721 if (l->first_case <= value && value <= l->last_case) {
9727 warningf(&statement->base.source_position,
9728 "enumeration value '%Y' not handled in switch",
9729 entry->base.symbol);
9736 * Parse a switch statement.
9738 static statement_t *parse_switch(void)
9740 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9744 PUSH_PARENT(statement);
9747 add_anchor_token(')');
9748 expression_t *const expr = parse_expression();
9749 mark_vars_read(expr, NULL);
9750 type_t * type = skip_typeref(expr->base.type);
9751 if (is_type_integer(type)) {
9752 type = promote_integer(type);
9753 if (warning.traditional) {
9754 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9755 warningf(&expr->base.source_position,
9756 "'%T' switch expression not converted to '%T' in ISO C",
9760 } else if (is_type_valid(type)) {
9761 errorf(&expr->base.source_position,
9762 "switch quantity is not an integer, but '%T'", type);
9763 type = type_error_type;
9765 statement->switchs.expression = create_implicit_cast(expr, type);
9767 rem_anchor_token(')');
9769 switch_statement_t *rem = current_switch;
9770 current_switch = &statement->switchs;
9771 statement->switchs.body = parse_statement();
9772 current_switch = rem;
9774 if (warning.switch_default &&
9775 statement->switchs.default_label == NULL) {
9776 warningf(&statement->base.source_position, "switch has no default case");
9778 if (warning.switch_enum)
9779 check_enum_cases(&statement->switchs);
9785 return create_invalid_statement();
9788 static statement_t *parse_loop_body(statement_t *const loop)
9790 statement_t *const rem = current_loop;
9791 current_loop = loop;
9793 statement_t *const body = parse_statement();
9800 * Parse a while statement.
9802 static statement_t *parse_while(void)
9804 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9808 PUSH_PARENT(statement);
9811 add_anchor_token(')');
9812 expression_t *const cond = parse_expression();
9813 statement->whiles.condition = cond;
9814 /* §6.8.5:2 The controlling expression of an iteration statement shall
9815 * have scalar type. */
9816 semantic_condition(cond, "condition of 'while'-statement");
9817 mark_vars_read(cond, NULL);
9818 rem_anchor_token(')');
9821 statement->whiles.body = parse_loop_body(statement);
9827 return create_invalid_statement();
9831 * Parse a do statement.
9833 static statement_t *parse_do(void)
9835 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9839 PUSH_PARENT(statement);
9841 add_anchor_token(T_while);
9842 statement->do_while.body = parse_loop_body(statement);
9843 rem_anchor_token(T_while);
9847 add_anchor_token(')');
9848 expression_t *const cond = parse_expression();
9849 statement->do_while.condition = cond;
9850 /* §6.8.5:2 The controlling expression of an iteration statement shall
9851 * have scalar type. */
9852 semantic_condition(cond, "condition of 'do-while'-statement");
9853 mark_vars_read(cond, NULL);
9854 rem_anchor_token(')');
9862 return create_invalid_statement();
9866 * Parse a for statement.
9868 static statement_t *parse_for(void)
9870 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9874 PUSH_PARENT(statement);
9876 size_t const top = environment_top();
9877 scope_push(&statement->fors.scope);
9880 add_anchor_token(')');
9882 if (token.type == ';') {
9884 } else if (is_declaration_specifier(&token, false)) {
9885 parse_declaration(record_entity);
9887 add_anchor_token(';');
9888 expression_t *const init = parse_expression();
9889 statement->fors.initialisation = init;
9890 mark_vars_read(init, VAR_ANY);
9891 if (warning.unused_value && !expression_has_effect(init)) {
9892 warningf(&init->base.source_position,
9893 "initialisation of 'for'-statement has no effect");
9895 rem_anchor_token(';');
9899 if (token.type != ';') {
9900 add_anchor_token(';');
9901 expression_t *const cond = parse_expression();
9902 statement->fors.condition = cond;
9903 /* §6.8.5:2 The controlling expression of an iteration statement shall
9904 * have scalar type. */
9905 semantic_condition(cond, "condition of 'for'-statement");
9906 mark_vars_read(cond, NULL);
9907 rem_anchor_token(';');
9910 if (token.type != ')') {
9911 expression_t *const step = parse_expression();
9912 statement->fors.step = step;
9913 mark_vars_read(step, VAR_ANY);
9914 if (warning.unused_value && !expression_has_effect(step)) {
9915 warningf(&step->base.source_position,
9916 "step of 'for'-statement has no effect");
9920 rem_anchor_token(')');
9921 statement->fors.body = parse_loop_body(statement);
9923 assert(current_scope == &statement->fors.scope);
9925 environment_pop_to(top);
9932 rem_anchor_token(')');
9933 assert(current_scope == &statement->fors.scope);
9935 environment_pop_to(top);
9937 return create_invalid_statement();
9941 * Parse a goto statement.
9943 static statement_t *parse_goto(void)
9945 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9948 if (GNU_MODE && token.type == '*') {
9950 expression_t *expression = parse_expression();
9951 mark_vars_read(expression, NULL);
9953 /* Argh: although documentation says the expression must be of type void*,
9954 * gcc accepts anything that can be casted into void* without error */
9955 type_t *type = expression->base.type;
9957 if (type != type_error_type) {
9958 if (!is_type_pointer(type) && !is_type_integer(type)) {
9959 errorf(&expression->base.source_position,
9960 "cannot convert to a pointer type");
9961 } else if (warning.other && type != type_void_ptr) {
9962 warningf(&expression->base.source_position,
9963 "type of computed goto expression should be 'void*' not '%T'", type);
9965 expression = create_implicit_cast(expression, type_void_ptr);
9968 statement->gotos.expression = expression;
9970 if (token.type != T_IDENTIFIER) {
9972 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9974 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9978 symbol_t *symbol = token.v.symbol;
9981 statement->gotos.label = get_label(symbol);
9984 /* remember the goto's in a list for later checking */
9985 *goto_anchor = &statement->gotos;
9986 goto_anchor = &statement->gotos.next;
9992 return create_invalid_statement();
9996 * Parse a continue statement.
9998 static statement_t *parse_continue(void)
10000 if (current_loop == NULL) {
10001 errorf(HERE, "continue statement not within loop");
10004 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
10014 * Parse a break statement.
10016 static statement_t *parse_break(void)
10018 if (current_switch == NULL && current_loop == NULL) {
10019 errorf(HERE, "break statement not within loop or switch");
10022 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
10032 * Parse a __leave statement.
10034 static statement_t *parse_leave_statement(void)
10036 if (current_try == NULL) {
10037 errorf(HERE, "__leave statement not within __try");
10040 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10050 * Check if a given entity represents a local variable.
10052 static bool is_local_variable(const entity_t *entity)
10054 if (entity->kind != ENTITY_VARIABLE)
10057 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10058 case STORAGE_CLASS_AUTO:
10059 case STORAGE_CLASS_REGISTER: {
10060 const type_t *type = skip_typeref(entity->declaration.type);
10061 if (is_type_function(type)) {
10073 * Check if a given expression represents a local variable.
10075 static bool expression_is_local_variable(const expression_t *expression)
10077 if (expression->base.kind != EXPR_REFERENCE) {
10080 const entity_t *entity = expression->reference.entity;
10081 return is_local_variable(entity);
10085 * Check if a given expression represents a local variable and
10086 * return its declaration then, else return NULL.
10088 entity_t *expression_is_variable(const expression_t *expression)
10090 if (expression->base.kind != EXPR_REFERENCE) {
10093 entity_t *entity = expression->reference.entity;
10094 if (entity->kind != ENTITY_VARIABLE)
10101 * Parse a return statement.
10103 static statement_t *parse_return(void)
10107 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10109 expression_t *return_value = NULL;
10110 if (token.type != ';') {
10111 return_value = parse_expression();
10112 mark_vars_read(return_value, NULL);
10115 const type_t *const func_type = skip_typeref(current_function->base.type);
10116 assert(is_type_function(func_type));
10117 type_t *const return_type = skip_typeref(func_type->function.return_type);
10119 if (return_value != NULL) {
10120 type_t *return_value_type = skip_typeref(return_value->base.type);
10122 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
10123 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10124 if (warning.other) {
10125 warningf(&statement->base.source_position,
10126 "'return' with a value, in function returning void");
10128 return_value = NULL;
10130 assign_error_t error = semantic_assign(return_type, return_value);
10131 report_assign_error(error, return_type, return_value, "'return'",
10132 &statement->base.source_position);
10133 return_value = create_implicit_cast(return_value, return_type);
10135 /* check for returning address of a local var */
10136 if (warning.other && return_value != NULL
10137 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10138 const expression_t *expression = return_value->unary.value;
10139 if (expression_is_local_variable(expression)) {
10140 warningf(&statement->base.source_position,
10141 "function returns address of local variable");
10144 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10145 warningf(&statement->base.source_position,
10146 "'return' without value, in function returning non-void");
10148 statement->returns.value = return_value;
10157 * Parse a declaration statement.
10159 static statement_t *parse_declaration_statement(void)
10161 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10163 entity_t *before = current_scope->last_entity;
10165 parse_external_declaration();
10167 parse_declaration(record_entity);
10169 if (before == NULL) {
10170 statement->declaration.declarations_begin = current_scope->entities;
10172 statement->declaration.declarations_begin = before->base.next;
10174 statement->declaration.declarations_end = current_scope->last_entity;
10180 * Parse an expression statement, ie. expr ';'.
10182 static statement_t *parse_expression_statement(void)
10184 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10186 expression_t *const expr = parse_expression();
10187 statement->expression.expression = expr;
10188 mark_vars_read(expr, VAR_ANY);
10197 * Parse a microsoft __try { } __finally { } or
10198 * __try{ } __except() { }
10200 static statement_t *parse_ms_try_statment(void)
10202 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10205 PUSH_PARENT(statement);
10207 ms_try_statement_t *rem = current_try;
10208 current_try = &statement->ms_try;
10209 statement->ms_try.try_statement = parse_compound_statement(false);
10214 if (token.type == T___except) {
10217 add_anchor_token(')');
10218 expression_t *const expr = parse_expression();
10219 mark_vars_read(expr, NULL);
10220 type_t * type = skip_typeref(expr->base.type);
10221 if (is_type_integer(type)) {
10222 type = promote_integer(type);
10223 } else if (is_type_valid(type)) {
10224 errorf(&expr->base.source_position,
10225 "__expect expression is not an integer, but '%T'", type);
10226 type = type_error_type;
10228 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10229 rem_anchor_token(')');
10231 statement->ms_try.final_statement = parse_compound_statement(false);
10232 } else if (token.type == T__finally) {
10234 statement->ms_try.final_statement = parse_compound_statement(false);
10236 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10237 return create_invalid_statement();
10241 return create_invalid_statement();
10244 static statement_t *parse_empty_statement(void)
10246 if (warning.empty_statement) {
10247 warningf(HERE, "statement is empty");
10249 statement_t *const statement = create_empty_statement();
10254 static statement_t *parse_local_label_declaration(void)
10256 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10260 entity_t *begin = NULL, *end = NULL;
10263 if (token.type != T_IDENTIFIER) {
10264 parse_error_expected("while parsing local label declaration",
10265 T_IDENTIFIER, NULL);
10268 symbol_t *symbol = token.v.symbol;
10269 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10270 if (entity != NULL && entity->base.parent_scope == current_scope) {
10271 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10272 symbol, &entity->base.source_position);
10274 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10276 entity->base.parent_scope = current_scope;
10277 entity->base.namespc = NAMESPACE_LABEL;
10278 entity->base.source_position = token.source_position;
10279 entity->base.symbol = symbol;
10282 end->base.next = entity;
10287 environment_push(entity);
10291 if (token.type != ',')
10297 statement->declaration.declarations_begin = begin;
10298 statement->declaration.declarations_end = end;
10302 static void parse_namespace_definition(void)
10306 entity_t *entity = NULL;
10307 symbol_t *symbol = NULL;
10309 if (token.type == T_IDENTIFIER) {
10310 symbol = token.v.symbol;
10313 entity = get_entity(symbol, NAMESPACE_NORMAL);
10314 if (entity != NULL && entity->kind != ENTITY_NAMESPACE
10315 && entity->base.parent_scope == current_scope) {
10316 error_redefined_as_different_kind(&token.source_position,
10317 entity, ENTITY_NAMESPACE);
10322 if (entity == NULL) {
10323 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10324 entity->base.symbol = symbol;
10325 entity->base.source_position = token.source_position;
10326 entity->base.namespc = NAMESPACE_NORMAL;
10327 entity->base.parent_scope = current_scope;
10330 if (token.type == '=') {
10331 /* TODO: parse namespace alias */
10332 panic("namespace alias definition not supported yet");
10335 environment_push(entity);
10336 append_entity(current_scope, entity);
10338 size_t const top = environment_top();
10339 scope_push(&entity->namespacee.members);
10346 assert(current_scope == &entity->namespacee.members);
10348 environment_pop_to(top);
10352 * Parse a statement.
10353 * There's also parse_statement() which additionally checks for
10354 * "statement has no effect" warnings
10356 static statement_t *intern_parse_statement(void)
10358 statement_t *statement = NULL;
10360 /* declaration or statement */
10361 add_anchor_token(';');
10362 switch (token.type) {
10363 case T_IDENTIFIER: {
10364 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10365 if (la1_type == ':') {
10366 statement = parse_label_statement();
10367 } else if (is_typedef_symbol(token.v.symbol)) {
10368 statement = parse_declaration_statement();
10370 /* it's an identifier, the grammar says this must be an
10371 * expression statement. However it is common that users mistype
10372 * declaration types, so we guess a bit here to improve robustness
10373 * for incorrect programs */
10374 switch (la1_type) {
10377 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10378 goto expression_statment;
10383 statement = parse_declaration_statement();
10387 expression_statment:
10388 statement = parse_expression_statement();
10395 case T___extension__:
10396 /* This can be a prefix to a declaration or an expression statement.
10397 * We simply eat it now and parse the rest with tail recursion. */
10400 } while (token.type == T___extension__);
10401 bool old_gcc_extension = in_gcc_extension;
10402 in_gcc_extension = true;
10403 statement = intern_parse_statement();
10404 in_gcc_extension = old_gcc_extension;
10408 statement = parse_declaration_statement();
10412 statement = parse_local_label_declaration();
10415 case ';': statement = parse_empty_statement(); break;
10416 case '{': statement = parse_compound_statement(false); break;
10417 case T___leave: statement = parse_leave_statement(); break;
10418 case T___try: statement = parse_ms_try_statment(); break;
10419 case T_asm: statement = parse_asm_statement(); break;
10420 case T_break: statement = parse_break(); break;
10421 case T_case: statement = parse_case_statement(); break;
10422 case T_continue: statement = parse_continue(); break;
10423 case T_default: statement = parse_default_statement(); break;
10424 case T_do: statement = parse_do(); break;
10425 case T_for: statement = parse_for(); break;
10426 case T_goto: statement = parse_goto(); break;
10427 case T_if: statement = parse_if(); break;
10428 case T_return: statement = parse_return(); break;
10429 case T_switch: statement = parse_switch(); break;
10430 case T_while: statement = parse_while(); break;
10433 statement = parse_expression_statement();
10437 errorf(HERE, "unexpected token %K while parsing statement", &token);
10438 statement = create_invalid_statement();
10443 rem_anchor_token(';');
10445 assert(statement != NULL
10446 && statement->base.source_position.input_name != NULL);
10452 * parse a statement and emits "statement has no effect" warning if needed
10453 * (This is really a wrapper around intern_parse_statement with check for 1
10454 * single warning. It is needed, because for statement expressions we have
10455 * to avoid the warning on the last statement)
10457 static statement_t *parse_statement(void)
10459 statement_t *statement = intern_parse_statement();
10461 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10462 expression_t *expression = statement->expression.expression;
10463 if (!expression_has_effect(expression)) {
10464 warningf(&expression->base.source_position,
10465 "statement has no effect");
10473 * Parse a compound statement.
10475 static statement_t *parse_compound_statement(bool inside_expression_statement)
10477 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10479 PUSH_PARENT(statement);
10482 add_anchor_token('}');
10484 size_t const top = environment_top();
10485 scope_push(&statement->compound.scope);
10487 statement_t **anchor = &statement->compound.statements;
10488 bool only_decls_so_far = true;
10489 while (token.type != '}') {
10490 if (token.type == T_EOF) {
10491 errorf(&statement->base.source_position,
10492 "EOF while parsing compound statement");
10495 statement_t *sub_statement = intern_parse_statement();
10496 if (is_invalid_statement(sub_statement)) {
10497 /* an error occurred. if we are at an anchor, return */
10503 if (warning.declaration_after_statement) {
10504 if (sub_statement->kind != STATEMENT_DECLARATION) {
10505 only_decls_so_far = false;
10506 } else if (!only_decls_so_far) {
10507 warningf(&sub_statement->base.source_position,
10508 "ISO C90 forbids mixed declarations and code");
10512 *anchor = sub_statement;
10514 while (sub_statement->base.next != NULL)
10515 sub_statement = sub_statement->base.next;
10517 anchor = &sub_statement->base.next;
10521 /* look over all statements again to produce no effect warnings */
10522 if (warning.unused_value) {
10523 statement_t *sub_statement = statement->compound.statements;
10524 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10525 if (sub_statement->kind != STATEMENT_EXPRESSION)
10527 /* don't emit a warning for the last expression in an expression
10528 * statement as it has always an effect */
10529 if (inside_expression_statement && sub_statement->base.next == NULL)
10532 expression_t *expression = sub_statement->expression.expression;
10533 if (!expression_has_effect(expression)) {
10534 warningf(&expression->base.source_position,
10535 "statement has no effect");
10541 rem_anchor_token('}');
10542 assert(current_scope == &statement->compound.scope);
10544 environment_pop_to(top);
10551 * Check for unused global static functions and variables
10553 static void check_unused_globals(void)
10555 if (!warning.unused_function && !warning.unused_variable)
10558 for (const entity_t *entity = file_scope->entities; entity != NULL;
10559 entity = entity->base.next) {
10560 if (!is_declaration(entity))
10563 const declaration_t *declaration = &entity->declaration;
10564 if (declaration->used ||
10565 declaration->modifiers & DM_UNUSED ||
10566 declaration->modifiers & DM_USED ||
10567 declaration->storage_class != STORAGE_CLASS_STATIC)
10570 type_t *const type = declaration->type;
10572 if (entity->kind == ENTITY_FUNCTION) {
10573 /* inhibit warning for static inline functions */
10574 if (entity->function.is_inline)
10577 s = entity->function.statement != NULL ? "defined" : "declared";
10582 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10583 type, declaration->base.symbol, s);
10587 static void parse_global_asm(void)
10589 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10594 statement->asms.asm_text = parse_string_literals();
10595 statement->base.next = unit->global_asm;
10596 unit->global_asm = statement;
10604 static void parse_linkage_specification(void)
10607 assert(token.type == T_STRING_LITERAL);
10609 const char *linkage = parse_string_literals().begin;
10611 linkage_kind_t old_linkage = current_linkage;
10612 linkage_kind_t new_linkage;
10613 if (strcmp(linkage, "C") == 0) {
10614 new_linkage = LINKAGE_C;
10615 } else if (strcmp(linkage, "C++") == 0) {
10616 new_linkage = LINKAGE_CXX;
10618 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10619 new_linkage = LINKAGE_INVALID;
10621 current_linkage = new_linkage;
10623 if (token.type == '{') {
10632 assert(current_linkage == new_linkage);
10633 current_linkage = old_linkage;
10636 static void parse_external(void)
10638 switch (token.type) {
10639 DECLARATION_START_NO_EXTERN
10641 case T___extension__:
10642 case '(': /* for function declarations with implicit return type and
10643 * parenthesized declarator, i.e. (f)(void); */
10644 parse_external_declaration();
10648 if (look_ahead(1)->type == T_STRING_LITERAL) {
10649 parse_linkage_specification();
10651 parse_external_declaration();
10656 parse_global_asm();
10660 parse_namespace_definition();
10664 if (!strict_mode) {
10666 warningf(HERE, "stray ';' outside of function");
10673 errorf(HERE, "stray %K outside of function", &token);
10674 if (token.type == '(' || token.type == '{' || token.type == '[')
10675 eat_until_matching_token(token.type);
10681 static void parse_externals(void)
10683 add_anchor_token('}');
10684 add_anchor_token(T_EOF);
10687 unsigned char token_anchor_copy[T_LAST_TOKEN];
10688 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10691 while (token.type != T_EOF && token.type != '}') {
10693 bool anchor_leak = false;
10694 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10695 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10697 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10698 anchor_leak = true;
10701 if (in_gcc_extension) {
10702 errorf(HERE, "Leaked __extension__");
10703 anchor_leak = true;
10713 rem_anchor_token(T_EOF);
10714 rem_anchor_token('}');
10718 * Parse a translation unit.
10720 static void parse_translation_unit(void)
10722 add_anchor_token(T_EOF);
10727 if (token.type == T_EOF)
10730 errorf(HERE, "stray %K outside of function", &token);
10731 if (token.type == '(' || token.type == '{' || token.type == '[')
10732 eat_until_matching_token(token.type);
10740 * @return the translation unit or NULL if errors occurred.
10742 void start_parsing(void)
10744 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10745 label_stack = NEW_ARR_F(stack_entry_t, 0);
10746 diagnostic_count = 0;
10750 type_set_output(stderr);
10751 ast_set_output(stderr);
10753 assert(unit == NULL);
10754 unit = allocate_ast_zero(sizeof(unit[0]));
10756 assert(file_scope == NULL);
10757 file_scope = &unit->scope;
10759 assert(current_scope == NULL);
10760 scope_push(&unit->scope);
10763 translation_unit_t *finish_parsing(void)
10765 /* do NOT use scope_pop() here, this will crash, will it by hand */
10766 assert(current_scope == &unit->scope);
10767 current_scope = NULL;
10769 assert(file_scope == &unit->scope);
10770 check_unused_globals();
10773 DEL_ARR_F(environment_stack);
10774 DEL_ARR_F(label_stack);
10776 translation_unit_t *result = unit;
10783 lookahead_bufpos = 0;
10784 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10787 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10788 parse_translation_unit();
10792 * Initialize the parser.
10794 void init_parser(void)
10796 sym_anonymous = symbol_table_insert("<anonymous>");
10798 if (c_mode & _MS) {
10799 /* add predefined symbols for extended-decl-modifier */
10800 sym_align = symbol_table_insert("align");
10801 sym_allocate = symbol_table_insert("allocate");
10802 sym_dllimport = symbol_table_insert("dllimport");
10803 sym_dllexport = symbol_table_insert("dllexport");
10804 sym_naked = symbol_table_insert("naked");
10805 sym_noinline = symbol_table_insert("noinline");
10806 sym_noreturn = symbol_table_insert("noreturn");
10807 sym_nothrow = symbol_table_insert("nothrow");
10808 sym_novtable = symbol_table_insert("novtable");
10809 sym_property = symbol_table_insert("property");
10810 sym_get = symbol_table_insert("get");
10811 sym_put = symbol_table_insert("put");
10812 sym_selectany = symbol_table_insert("selectany");
10813 sym_thread = symbol_table_insert("thread");
10814 sym_uuid = symbol_table_insert("uuid");
10815 sym_deprecated = symbol_table_insert("deprecated");
10816 sym_restrict = symbol_table_insert("restrict");
10817 sym_noalias = symbol_table_insert("noalias");
10819 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10821 init_expression_parsers();
10822 obstack_init(&temp_obst);
10824 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10825 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10829 * Terminate the parser.
10831 void exit_parser(void)
10833 obstack_free(&temp_obst, NULL);