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 /** if wchar_t is equal to unsigned short. */
45 bool opt_short_wchar_t =
52 //#define PRINT_TOKENS
53 #define MAX_LOOKAHEAD 2
61 typedef struct argument_list_t argument_list_t;
62 struct argument_list_t {
64 argument_list_t *next;
67 typedef struct gnu_attribute_t gnu_attribute_t;
68 struct gnu_attribute_t {
69 gnu_attribute_kind_t kind; /**< The kind of the GNU attribute. */
70 gnu_attribute_t *next;
71 bool invalid; /**< Set if this attribute had argument errors, */
72 bool have_arguments; /**< True, if this attribute has arguments. */
76 atomic_type_kind_t akind;
77 long argument; /**< Single argument. */
78 argument_list_t *arguments; /**< List of argument expressions. */
82 typedef struct declaration_specifiers_t declaration_specifiers_t;
83 struct declaration_specifiers_t {
84 source_position_t source_position;
85 storage_class_t storage_class;
86 unsigned char alignment; /**< Alignment, 0 if not set. */
89 decl_modifiers_t modifiers; /**< declaration modifiers */
90 gnu_attribute_t *gnu_attributes; /**< list of GNU attributes */
91 const char *deprecated_string; /**< can be set if declaration was marked deprecated. */
92 symbol_t *get_property_sym; /**< the name of the get property if set. */
93 symbol_t *put_property_sym; /**< the name of the put property if set. */
98 * An environment for parsing initializers (and compound literals).
100 typedef struct parse_initializer_env_t {
101 type_t *type; /**< the type of the initializer. In case of an
102 array type with unspecified size this gets
103 adjusted to the actual size. */
104 entity_t *entity; /**< the variable that is initialized if any */
105 bool must_be_constant;
106 } parse_initializer_env_t;
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 /** The global file scope. */
119 static scope_t *file_scope = NULL;
120 /** The current scope. */
121 static scope_t *scope = NULL;
122 /** Point to the current function declaration if inside a function. */
123 static function_t *current_function = NULL;
124 static entity_t *current_init_decl = NULL;
125 static switch_statement_t *current_switch = NULL;
126 static statement_t *current_loop = NULL;
127 static statement_t *current_parent = NULL;
128 static ms_try_statement_t *current_try = NULL;
129 static goto_statement_t *goto_first = NULL;
130 static goto_statement_t *goto_last = NULL;
131 static label_statement_t *label_first = NULL;
132 static label_statement_t *label_last = NULL;
133 /** current translation unit. */
134 static translation_unit_t *unit = NULL;
135 /** true if we are in a type property context (evaluation only for type. */
136 static bool in_type_prop = false;
137 /** true in we are in a __extension__ context. */
138 static bool in_gcc_extension = false;
139 static struct obstack temp_obst;
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);
188 static void parse_compound_type_entries(compound_t *compound_declaration);
189 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
190 bool may_be_abstract,
191 bool create_compound_member);
192 static entity_t *record_entity(entity_t *entity, bool is_definition);
194 static void semantic_comparison(binary_expression_t *expression);
196 #define STORAGE_CLASSES \
204 #define TYPE_QUALIFIERS \
209 case T__forceinline: \
210 case T___attribute__:
212 #ifdef PROVIDE_COMPLEX
213 #define COMPLEX_SPECIFIERS \
215 #define IMAGINARY_SPECIFIERS \
218 #define COMPLEX_SPECIFIERS
219 #define IMAGINARY_SPECIFIERS
222 #define TYPE_SPECIFIERS \
224 case T___builtin_va_list: \
243 #define DECLARATION_START \
248 #define TYPENAME_START \
252 #define EXPRESSION_START \
261 case T_CHARACTER_CONSTANT: \
262 case T_FLOATINGPOINT: \
266 case T_STRING_LITERAL: \
267 case T_WIDE_CHARACTER_CONSTANT: \
268 case T_WIDE_STRING_LITERAL: \
269 case T___FUNCDNAME__: \
270 case T___FUNCSIG__: \
271 case T___FUNCTION__: \
272 case T___PRETTY_FUNCTION__: \
273 case T___alignof__: \
274 case T___builtin_alloca: \
275 case T___builtin_classify_type: \
276 case T___builtin_constant_p: \
277 case T___builtin_expect: \
278 case T___builtin_huge_val: \
279 case T___builtin_inf: \
280 case T___builtin_inff: \
281 case T___builtin_infl: \
282 case T___builtin_isgreater: \
283 case T___builtin_isgreaterequal: \
284 case T___builtin_isless: \
285 case T___builtin_islessequal: \
286 case T___builtin_islessgreater: \
287 case T___builtin_isunordered: \
288 case T___builtin_nan: \
289 case T___builtin_nanf: \
290 case T___builtin_nanl: \
291 case T___builtin_offsetof: \
292 case T___builtin_prefetch: \
293 case T___builtin_va_arg: \
294 case T___builtin_va_end: \
295 case T___builtin_va_start: \
306 * Allocate an AST node with given size and
307 * initialize all fields with zero.
309 static void *allocate_ast_zero(size_t size)
311 void *res = allocate_ast(size);
312 memset(res, 0, size);
316 static size_t get_entity_struct_size(entity_kind_t kind)
318 static const size_t sizes[] = {
319 [ENTITY_VARIABLE] = sizeof(variable_t),
320 [ENTITY_COMPOUND_MEMBER] = sizeof(variable_t),
321 [ENTITY_FUNCTION] = sizeof(function_t),
322 [ENTITY_TYPEDEF] = sizeof(typedef_t),
323 [ENTITY_STRUCT] = sizeof(compound_t),
324 [ENTITY_UNION] = sizeof(compound_t),
325 [ENTITY_ENUM] = sizeof(enum_t),
326 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
327 [ENTITY_LABEL] = sizeof(label_t),
328 [ENTITY_LOCAL_LABEL] = sizeof(label_t)
330 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
331 assert(sizes[kind] != 0);
335 static entity_t *allocate_entity_zero(entity_kind_t kind)
337 size_t size = get_entity_struct_size(kind);
338 entity_t *entity = allocate_ast_zero(size);
344 * Returns the size of a statement node.
346 * @param kind the statement kind
348 static size_t get_statement_struct_size(statement_kind_t kind)
350 static const size_t sizes[] = {
351 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
352 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
353 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
354 [STATEMENT_RETURN] = sizeof(return_statement_t),
355 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
356 [STATEMENT_LOCAL_LABEL] = sizeof(local_label_statement_t),
357 [STATEMENT_IF] = sizeof(if_statement_t),
358 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
359 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
360 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
361 [STATEMENT_BREAK] = sizeof(statement_base_t),
362 [STATEMENT_GOTO] = sizeof(goto_statement_t),
363 [STATEMENT_LABEL] = sizeof(label_statement_t),
364 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
365 [STATEMENT_WHILE] = sizeof(while_statement_t),
366 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
367 [STATEMENT_FOR] = sizeof(for_statement_t),
368 [STATEMENT_ASM] = sizeof(asm_statement_t),
369 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
370 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
372 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
373 assert(sizes[kind] != 0);
378 * Returns the size of an expression node.
380 * @param kind the expression kind
382 static size_t get_expression_struct_size(expression_kind_t kind)
384 static const size_t sizes[] = {
385 [EXPR_INVALID] = sizeof(expression_base_t),
386 [EXPR_REFERENCE] = sizeof(reference_expression_t),
387 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
388 [EXPR_CONST] = sizeof(const_expression_t),
389 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
390 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
391 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
392 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
393 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
394 [EXPR_CALL] = sizeof(call_expression_t),
395 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
396 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
397 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
398 [EXPR_SELECT] = sizeof(select_expression_t),
399 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
400 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
401 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
402 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
403 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
404 [EXPR_BUILTIN_SYMBOL] = sizeof(builtin_symbol_expression_t),
405 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
406 [EXPR_BUILTIN_PREFETCH] = sizeof(builtin_prefetch_expression_t),
407 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
408 [EXPR_VA_START] = sizeof(va_start_expression_t),
409 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
410 [EXPR_STATEMENT] = sizeof(statement_expression_t),
411 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
413 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
414 return sizes[EXPR_UNARY_FIRST];
416 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
417 return sizes[EXPR_BINARY_FIRST];
419 assert(kind < sizeof(sizes) / sizeof(sizes[0]));
420 assert(sizes[kind] != 0);
425 * Allocate a statement node of given kind and initialize all
428 static statement_t *allocate_statement_zero(statement_kind_t kind)
430 size_t size = get_statement_struct_size(kind);
431 statement_t *res = allocate_ast_zero(size);
433 res->base.kind = kind;
434 res->base.parent = current_parent;
435 res->base.source_position = token.source_position;
440 * Allocate an expression node of given kind and initialize all
443 static expression_t *allocate_expression_zero(expression_kind_t kind)
445 size_t size = get_expression_struct_size(kind);
446 expression_t *res = allocate_ast_zero(size);
448 res->base.kind = kind;
449 res->base.type = type_error_type;
450 res->base.source_position = token.source_position;
455 * Creates a new invalid expression.
457 static expression_t *create_invalid_expression(void)
459 return allocate_expression_zero(EXPR_INVALID);
463 * Creates a new invalid statement.
465 static statement_t *create_invalid_statement(void)
467 return allocate_statement_zero(STATEMENT_INVALID);
471 * Allocate a new empty statement.
473 static statement_t *create_empty_statement(void)
475 return allocate_statement_zero(STATEMENT_EMPTY);
479 * Returns the size of a type node.
481 * @param kind the type kind
483 static size_t get_type_struct_size(type_kind_t kind)
485 static const size_t sizes[] = {
486 [TYPE_ATOMIC] = sizeof(atomic_type_t),
487 [TYPE_COMPLEX] = sizeof(complex_type_t),
488 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
489 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
490 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
491 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
492 [TYPE_ENUM] = sizeof(enum_type_t),
493 [TYPE_FUNCTION] = sizeof(function_type_t),
494 [TYPE_POINTER] = sizeof(pointer_type_t),
495 [TYPE_ARRAY] = sizeof(array_type_t),
496 [TYPE_BUILTIN] = sizeof(builtin_type_t),
497 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
498 [TYPE_TYPEOF] = sizeof(typeof_type_t),
500 assert(sizeof(sizes) / sizeof(sizes[0]) == (int) TYPE_TYPEOF + 1);
501 assert(kind <= TYPE_TYPEOF);
502 assert(sizes[kind] != 0);
507 * Allocate a type node of given kind and initialize all
510 * @param kind type kind to allocate
512 static type_t *allocate_type_zero(type_kind_t kind)
514 size_t size = get_type_struct_size(kind);
515 type_t *res = obstack_alloc(type_obst, size);
516 memset(res, 0, size);
517 res->base.kind = kind;
523 * Returns the size of an initializer node.
525 * @param kind the initializer kind
527 static size_t get_initializer_size(initializer_kind_t kind)
529 static const size_t sizes[] = {
530 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
531 [INITIALIZER_STRING] = sizeof(initializer_string_t),
532 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
533 [INITIALIZER_LIST] = sizeof(initializer_list_t),
534 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
536 assert(kind < sizeof(sizes) / sizeof(*sizes));
537 assert(sizes[kind] != 0);
542 * Allocate an initializer node of given kind and initialize all
545 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
547 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
554 * Free a type from the type obstack.
556 static void free_type(void *type)
558 obstack_free(type_obst, type);
562 * Returns the index of the top element of the environment stack.
564 static size_t environment_top(void)
566 return ARR_LEN(environment_stack);
570 * Returns the index of the top element of the global label stack.
572 static size_t label_top(void)
574 return ARR_LEN(label_stack);
578 * Return the next token.
580 static inline void next_token(void)
582 token = lookahead_buffer[lookahead_bufpos];
583 lookahead_buffer[lookahead_bufpos] = lexer_token;
586 lookahead_bufpos = (lookahead_bufpos+1) % MAX_LOOKAHEAD;
589 print_token(stderr, &token);
590 fprintf(stderr, "\n");
595 * Return the next token with a given lookahead.
597 static inline const token_t *look_ahead(int num)
599 assert(num > 0 && num <= MAX_LOOKAHEAD);
600 int pos = (lookahead_bufpos+num-1) % MAX_LOOKAHEAD;
601 return &lookahead_buffer[pos];
605 * Adds a token to the token anchor set (a multi-set).
607 static void add_anchor_token(int token_type)
609 assert(0 <= token_type && token_type < T_LAST_TOKEN);
610 ++token_anchor_set[token_type];
613 static int save_and_reset_anchor_state(int token_type)
615 assert(0 <= token_type && token_type < T_LAST_TOKEN);
616 int count = token_anchor_set[token_type];
617 token_anchor_set[token_type] = 0;
621 static void restore_anchor_state(int token_type, int count)
623 assert(0 <= token_type && token_type < T_LAST_TOKEN);
624 token_anchor_set[token_type] = count;
628 * Remove a token from the token anchor set (a multi-set).
630 static void rem_anchor_token(int token_type)
632 assert(0 <= token_type && token_type < T_LAST_TOKEN);
633 assert(token_anchor_set[token_type] != 0);
634 --token_anchor_set[token_type];
637 static bool at_anchor(void)
641 return token_anchor_set[token.type];
645 * Eat tokens until a matching token is found.
647 static void eat_until_matching_token(int type)
651 case '(': end_token = ')'; break;
652 case '{': end_token = '}'; break;
653 case '[': end_token = ']'; break;
654 default: end_token = type; break;
657 unsigned parenthesis_count = 0;
658 unsigned brace_count = 0;
659 unsigned bracket_count = 0;
660 while (token.type != end_token ||
661 parenthesis_count != 0 ||
663 bracket_count != 0) {
664 switch (token.type) {
666 case '(': ++parenthesis_count; break;
667 case '{': ++brace_count; break;
668 case '[': ++bracket_count; break;
671 if (parenthesis_count > 0)
681 if (bracket_count > 0)
684 if (token.type == end_token &&
685 parenthesis_count == 0 &&
699 * Eat input tokens until an anchor is found.
701 static void eat_until_anchor(void)
703 while (token_anchor_set[token.type] == 0) {
704 if (token.type == '(' || token.type == '{' || token.type == '[')
705 eat_until_matching_token(token.type);
710 static void eat_block(void)
712 eat_until_matching_token('{');
713 if (token.type == '}')
717 #define eat(token_type) do { assert(token.type == (token_type)); next_token(); } while (0)
720 * Report a parse error because an expected token was not found.
723 #if defined __GNUC__ && __GNUC__ >= 4
724 __attribute__((sentinel))
726 void parse_error_expected(const char *message, ...)
728 if (message != NULL) {
729 errorf(HERE, "%s", message);
732 va_start(ap, message);
733 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
738 * Report a type error.
740 static void type_error(const char *msg, const source_position_t *source_position,
743 errorf(source_position, "%s, but found type '%T'", msg, type);
747 * Report an incompatible type.
749 static void type_error_incompatible(const char *msg,
750 const source_position_t *source_position, type_t *type1, type_t *type2)
752 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
757 * Expect the the current token is the expected token.
758 * If not, generate an error, eat the current statement,
759 * and goto the end_error label.
761 #define expect(expected) \
763 if (UNLIKELY(token.type != (expected))) { \
764 parse_error_expected(NULL, (expected), NULL); \
765 add_anchor_token(expected); \
766 eat_until_anchor(); \
767 if (token.type == expected) \
769 rem_anchor_token(expected); \
775 static void scope_push(scope_t *new_scope)
778 new_scope->depth = scope->depth + 1;
780 new_scope->parent = scope;
784 static void scope_pop(void)
786 scope = scope->parent;
790 * Search an entity by its symbol in a given namespace.
792 static entity_t *get_entity(const symbol_t *const symbol, namespace_t namespc)
794 entity_t *entity = symbol->entity;
795 for( ; entity != NULL; entity = entity->base.symbol_next) {
796 if (entity->base.namespc == namespc)
804 * pushs an entity on the environment stack and links the corresponding symbol
807 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
809 symbol_t *symbol = entity->base.symbol;
810 namespace_t namespc = entity->base.namespc;
811 assert(namespc != NAMESPACE_INVALID);
813 /* replace/add entity into entity list of the symbol */
816 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
821 /* replace an entry? */
822 if (iter->base.namespc == namespc) {
823 entity->base.symbol_next = iter->base.symbol_next;
829 /* remember old declaration */
831 entry.symbol = symbol;
832 entry.old_entity = iter;
833 entry.namespc = namespc;
834 ARR_APP1(stack_entry_t, *stack_ptr, entry);
838 * Push an entity on the environment stack.
840 static void environment_push(entity_t *entity)
842 assert(entity->base.source_position.input_name != NULL);
843 assert(entity->base.parent_scope != NULL);
844 stack_push(&environment_stack, entity);
848 * Push a declaration on the global label stack.
850 * @param declaration the declaration
852 static void label_push(entity_t *label)
854 /* we abuse the parameters scope as parent for the labels */
855 label->base.parent_scope = ¤t_function->parameters;
856 stack_push(&label_stack, label);
860 * pops symbols from the environment stack until @p new_top is the top element
862 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
864 stack_entry_t *stack = *stack_ptr;
865 size_t top = ARR_LEN(stack);
868 assert(new_top <= top);
872 for(i = top; i > new_top; --i) {
873 stack_entry_t *entry = &stack[i - 1];
875 entity_t *old_entity = entry->old_entity;
876 symbol_t *symbol = entry->symbol;
877 namespace_t namespc = entry->namespc;
879 /* replace with old_entity/remove */
882 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
884 assert(iter != NULL);
885 /* replace an entry? */
886 if (iter->base.namespc == namespc)
890 /* restore definition from outer scopes (if there was one) */
891 if (old_entity != NULL) {
892 old_entity->base.symbol_next = iter->base.symbol_next;
893 *anchor = old_entity;
895 /* remove entry from list */
896 *anchor = iter->base.symbol_next;
900 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
904 * Pop all entries from the environment stack until the new_top
907 * @param new_top the new stack top
909 static void environment_pop_to(size_t new_top)
911 stack_pop_to(&environment_stack, new_top);
915 * Pop all entries from the global label stack until the new_top
918 * @param new_top the new stack top
920 static void label_pop_to(size_t new_top)
922 stack_pop_to(&label_stack, new_top);
925 static int get_akind_rank(atomic_type_kind_t akind)
930 static int get_rank(const type_t *type)
932 assert(!is_typeref(type));
933 /* The C-standard allows promoting enums to int or unsigned int (see § 7.2.2
934 * and esp. footnote 108). However we can't fold constants (yet), so we
935 * can't decide whether unsigned int is possible, while int always works.
936 * (unsigned int would be preferable when possible... for stuff like
937 * struct { enum { ... } bla : 4; } ) */
938 if (type->kind == TYPE_ENUM)
939 return get_akind_rank(ATOMIC_TYPE_INT);
941 assert(type->kind == TYPE_ATOMIC);
942 return get_akind_rank(type->atomic.akind);
945 static type_t *promote_integer(type_t *type)
947 if (type->kind == TYPE_BITFIELD)
948 type = type->bitfield.base_type;
950 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
957 * Create a cast expression.
959 * @param expression the expression to cast
960 * @param dest_type the destination type
962 static expression_t *create_cast_expression(expression_t *expression,
965 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
967 cast->unary.value = expression;
968 cast->base.type = dest_type;
974 * Check if a given expression represents the 0 pointer constant.
976 static bool is_null_pointer_constant(const expression_t *expression)
978 /* skip void* cast */
979 if (expression->kind == EXPR_UNARY_CAST
980 || expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
981 expression = expression->unary.value;
984 /* TODO: not correct yet, should be any constant integer expression
985 * which evaluates to 0 */
986 if (expression->kind != EXPR_CONST)
989 type_t *const type = skip_typeref(expression->base.type);
990 if (!is_type_integer(type))
993 return expression->conste.v.int_value == 0;
997 * Create an implicit cast expression.
999 * @param expression the expression to cast
1000 * @param dest_type the destination type
1002 static expression_t *create_implicit_cast(expression_t *expression,
1005 type_t *const source_type = expression->base.type;
1007 if (source_type == dest_type)
1010 return create_cast_expression(expression, dest_type);
1013 typedef enum assign_error_t {
1015 ASSIGN_ERROR_INCOMPATIBLE,
1016 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1017 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1018 ASSIGN_WARNING_POINTER_FROM_INT,
1019 ASSIGN_WARNING_INT_FROM_POINTER
1022 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1023 const expression_t *const right,
1024 const char *context,
1025 const source_position_t *source_position)
1027 type_t *const orig_type_right = right->base.type;
1028 type_t *const type_left = skip_typeref(orig_type_left);
1029 type_t *const type_right = skip_typeref(orig_type_right);
1032 case ASSIGN_SUCCESS:
1034 case ASSIGN_ERROR_INCOMPATIBLE:
1035 errorf(source_position,
1036 "destination type '%T' in %s is incompatible with type '%T'",
1037 orig_type_left, context, orig_type_right);
1040 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1041 if (warning.other) {
1042 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1043 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1045 /* the left type has all qualifiers from the right type */
1046 unsigned missing_qualifiers
1047 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1048 warningf(source_position,
1049 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1050 orig_type_left, context, orig_type_right, missing_qualifiers);
1055 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1056 if (warning.other) {
1057 warningf(source_position,
1058 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1059 orig_type_left, context, right, orig_type_right);
1063 case ASSIGN_WARNING_POINTER_FROM_INT:
1064 if (warning.other) {
1065 warningf(source_position,
1066 "%s makes pointer '%T' from integer '%T' without a cast",
1067 context, orig_type_left, orig_type_right);
1071 case ASSIGN_WARNING_INT_FROM_POINTER:
1072 if (warning.other) {
1073 warningf(source_position,
1074 "%s makes integer '%T' from pointer '%T' without a cast",
1075 context, orig_type_left, orig_type_right);
1080 panic("invalid error value");
1084 /** Implements the rules from § 6.5.16.1 */
1085 static assign_error_t semantic_assign(type_t *orig_type_left,
1086 const expression_t *const right)
1088 type_t *const orig_type_right = right->base.type;
1089 type_t *const type_left = skip_typeref(orig_type_left);
1090 type_t *const type_right = skip_typeref(orig_type_right);
1092 if (is_type_pointer(type_left)) {
1093 if (is_null_pointer_constant(right)) {
1094 return ASSIGN_SUCCESS;
1095 } else if (is_type_pointer(type_right)) {
1096 type_t *points_to_left
1097 = skip_typeref(type_left->pointer.points_to);
1098 type_t *points_to_right
1099 = skip_typeref(type_right->pointer.points_to);
1100 assign_error_t res = ASSIGN_SUCCESS;
1102 /* the left type has all qualifiers from the right type */
1103 unsigned missing_qualifiers
1104 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1105 if (missing_qualifiers != 0) {
1106 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1109 points_to_left = get_unqualified_type(points_to_left);
1110 points_to_right = get_unqualified_type(points_to_right);
1112 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1115 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1116 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1117 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1120 if (!types_compatible(points_to_left, points_to_right)) {
1121 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1125 } else if (is_type_integer(type_right)) {
1126 return ASSIGN_WARNING_POINTER_FROM_INT;
1128 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1129 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1130 && is_type_pointer(type_right))) {
1131 return ASSIGN_SUCCESS;
1132 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1133 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1134 type_t *const unqual_type_left = get_unqualified_type(type_left);
1135 type_t *const unqual_type_right = get_unqualified_type(type_right);
1136 if (types_compatible(unqual_type_left, unqual_type_right)) {
1137 return ASSIGN_SUCCESS;
1139 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1140 return ASSIGN_WARNING_INT_FROM_POINTER;
1143 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1144 return ASSIGN_SUCCESS;
1146 return ASSIGN_ERROR_INCOMPATIBLE;
1149 static expression_t *parse_constant_expression(void)
1151 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1153 if (!is_constant_expression(result)) {
1154 errorf(&result->base.source_position,
1155 "expression '%E' is not constant\n", result);
1161 static expression_t *parse_assignment_expression(void)
1163 return parse_sub_expression(PREC_ASSIGNMENT);
1166 static type_t *make_global_typedef(const char *name, type_t *type)
1168 symbol_t *const symbol = symbol_table_insert(name);
1170 entity_t *const entity = allocate_entity_zero(ENTITY_TYPEDEF);
1171 entity->base.symbol = symbol;
1172 entity->base.source_position = builtin_source_position;
1173 entity->base.namespc = NAMESPACE_NORMAL;
1174 entity->typedefe.type = type;
1175 entity->typedefe.builtin = true;
1177 record_entity(entity, false);
1179 type_t *typedef_type = allocate_type_zero(TYPE_TYPEDEF);
1180 typedef_type->typedeft.typedefe = &entity->typedefe;
1182 return typedef_type;
1185 static string_t parse_string_literals(void)
1187 assert(token.type == T_STRING_LITERAL);
1188 string_t result = token.v.string;
1192 while (token.type == T_STRING_LITERAL) {
1193 result = concat_strings(&result, &token.v.string);
1200 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1201 [GNU_AK_CONST] = "const",
1202 [GNU_AK_VOLATILE] = "volatile",
1203 [GNU_AK_CDECL] = "cdecl",
1204 [GNU_AK_STDCALL] = "stdcall",
1205 [GNU_AK_FASTCALL] = "fastcall",
1206 [GNU_AK_DEPRECATED] = "deprecated",
1207 [GNU_AK_NOINLINE] = "noinline",
1208 [GNU_AK_NORETURN] = "noreturn",
1209 [GNU_AK_NAKED] = "naked",
1210 [GNU_AK_PURE] = "pure",
1211 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1212 [GNU_AK_MALLOC] = "malloc",
1213 [GNU_AK_WEAK] = "weak",
1214 [GNU_AK_CONSTRUCTOR] = "constructor",
1215 [GNU_AK_DESTRUCTOR] = "destructor",
1216 [GNU_AK_NOTHROW] = "nothrow",
1217 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1218 [GNU_AK_COMMON] = "common",
1219 [GNU_AK_NOCOMMON] = "nocommon",
1220 [GNU_AK_PACKED] = "packed",
1221 [GNU_AK_SHARED] = "shared",
1222 [GNU_AK_NOTSHARED] = "notshared",
1223 [GNU_AK_USED] = "used",
1224 [GNU_AK_UNUSED] = "unused",
1225 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1226 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1227 [GNU_AK_LONGCALL] = "longcall",
1228 [GNU_AK_SHORTCALL] = "shortcall",
1229 [GNU_AK_LONG_CALL] = "long_call",
1230 [GNU_AK_SHORT_CALL] = "short_call",
1231 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1232 [GNU_AK_INTERRUPT] = "interrupt",
1233 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1234 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1235 [GNU_AK_NESTING] = "nesting",
1236 [GNU_AK_NEAR] = "near",
1237 [GNU_AK_FAR] = "far",
1238 [GNU_AK_SIGNAL] = "signal",
1239 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1240 [GNU_AK_TINY_DATA] = "tiny_data",
1241 [GNU_AK_SAVEALL] = "saveall",
1242 [GNU_AK_FLATTEN] = "flatten",
1243 [GNU_AK_SSEREGPARM] = "sseregparm",
1244 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1245 [GNU_AK_RETURN_TWICE] = "return_twice",
1246 [GNU_AK_MAY_ALIAS] = "may_alias",
1247 [GNU_AK_MS_STRUCT] = "ms_struct",
1248 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1249 [GNU_AK_DLLIMPORT] = "dllimport",
1250 [GNU_AK_DLLEXPORT] = "dllexport",
1251 [GNU_AK_ALIGNED] = "aligned",
1252 [GNU_AK_ALIAS] = "alias",
1253 [GNU_AK_SECTION] = "section",
1254 [GNU_AK_FORMAT] = "format",
1255 [GNU_AK_FORMAT_ARG] = "format_arg",
1256 [GNU_AK_WEAKREF] = "weakref",
1257 [GNU_AK_NONNULL] = "nonnull",
1258 [GNU_AK_TLS_MODEL] = "tls_model",
1259 [GNU_AK_VISIBILITY] = "visibility",
1260 [GNU_AK_REGPARM] = "regparm",
1261 [GNU_AK_MODE] = "mode",
1262 [GNU_AK_MODEL] = "model",
1263 [GNU_AK_TRAP_EXIT] = "trap_exit",
1264 [GNU_AK_SP_SWITCH] = "sp_switch",
1265 [GNU_AK_SENTINEL] = "sentinel"
1269 * compare two string, ignoring double underscores on the second.
1271 static int strcmp_underscore(const char *s1, const char *s2)
1273 if (s2[0] == '_' && s2[1] == '_') {
1274 size_t len2 = strlen(s2);
1275 size_t len1 = strlen(s1);
1276 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1277 return strncmp(s1, s2+2, len2-4);
1281 return strcmp(s1, s2);
1285 * Allocate a new gnu temporal attribute.
1287 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1289 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1290 attribute->kind = kind;
1291 attribute->next = NULL;
1292 attribute->invalid = false;
1293 attribute->have_arguments = false;
1299 * parse one constant expression argument.
1301 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1303 expression_t *expression;
1304 add_anchor_token(')');
1305 expression = parse_constant_expression();
1306 rem_anchor_token(')');
1308 attribute->u.argument = fold_constant(expression);
1311 attribute->invalid = true;
1315 * parse a list of constant expressions arguments.
1317 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1319 argument_list_t **list = &attribute->u.arguments;
1320 argument_list_t *entry;
1321 expression_t *expression;
1322 add_anchor_token(')');
1323 add_anchor_token(',');
1325 expression = parse_constant_expression();
1326 entry = obstack_alloc(&temp_obst, sizeof(entry));
1327 entry->argument = fold_constant(expression);
1330 list = &entry->next;
1331 if (token.type != ',')
1335 rem_anchor_token(',');
1336 rem_anchor_token(')');
1340 attribute->invalid = true;
1344 * parse one string literal argument.
1346 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1349 add_anchor_token('(');
1350 if (token.type != T_STRING_LITERAL) {
1351 parse_error_expected("while parsing attribute directive",
1352 T_STRING_LITERAL, NULL);
1355 *string = parse_string_literals();
1356 rem_anchor_token('(');
1360 attribute->invalid = true;
1364 * parse one tls model.
1366 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1368 static const char *const tls_models[] = {
1374 string_t string = { NULL, 0 };
1375 parse_gnu_attribute_string_arg(attribute, &string);
1376 if (string.begin != NULL) {
1377 for(size_t i = 0; i < 4; ++i) {
1378 if (strcmp(tls_models[i], string.begin) == 0) {
1379 attribute->u.value = i;
1383 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1385 attribute->invalid = true;
1389 * parse one tls model.
1391 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1393 static const char *const visibilities[] = {
1399 string_t string = { NULL, 0 };
1400 parse_gnu_attribute_string_arg(attribute, &string);
1401 if (string.begin != NULL) {
1402 for(size_t i = 0; i < 4; ++i) {
1403 if (strcmp(visibilities[i], string.begin) == 0) {
1404 attribute->u.value = i;
1408 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1410 attribute->invalid = true;
1414 * parse one (code) model.
1416 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1418 static const char *const visibilities[] = {
1423 string_t string = { NULL, 0 };
1424 parse_gnu_attribute_string_arg(attribute, &string);
1425 if (string.begin != NULL) {
1426 for(int i = 0; i < 3; ++i) {
1427 if (strcmp(visibilities[i], string.begin) == 0) {
1428 attribute->u.value = i;
1432 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1434 attribute->invalid = true;
1437 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1439 /* TODO: find out what is allowed here... */
1441 /* at least: byte, word, pointer, list of machine modes
1442 * __XXX___ is interpreted as XXX */
1443 add_anchor_token(')');
1445 if (token.type != T_IDENTIFIER) {
1446 expect(T_IDENTIFIER);
1449 /* This isn't really correct, the backend should provide a list of machine
1450 * specific modes (according to gcc philosophy that is...) */
1451 const char *symbol_str = token.v.symbol->string;
1452 if (strcmp_underscore("QI", symbol_str) == 0 ||
1453 strcmp_underscore("byte", symbol_str) == 0) {
1454 attribute->u.akind = ATOMIC_TYPE_CHAR;
1455 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1456 attribute->u.akind = ATOMIC_TYPE_SHORT;
1457 } else if (strcmp_underscore("SI", symbol_str) == 0
1458 || strcmp_underscore("word", symbol_str) == 0
1459 || strcmp_underscore("pointer", symbol_str) == 0) {
1460 attribute->u.akind = ATOMIC_TYPE_INT;
1461 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1462 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1465 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1466 attribute->invalid = true;
1470 rem_anchor_token(')');
1474 attribute->invalid = true;
1478 * parse one interrupt argument.
1480 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1482 static const char *const interrupts[] = {
1489 string_t string = { NULL, 0 };
1490 parse_gnu_attribute_string_arg(attribute, &string);
1491 if (string.begin != NULL) {
1492 for(size_t i = 0; i < 5; ++i) {
1493 if (strcmp(interrupts[i], string.begin) == 0) {
1494 attribute->u.value = i;
1498 errorf(HERE, "'%s' is not an interrupt", string.begin);
1500 attribute->invalid = true;
1504 * parse ( identifier, const expression, const expression )
1506 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1508 static const char *const format_names[] = {
1516 if (token.type != T_IDENTIFIER) {
1517 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1520 const char *name = token.v.symbol->string;
1521 for(i = 0; i < 4; ++i) {
1522 if (strcmp_underscore(format_names[i], name) == 0)
1526 if (warning.attribute)
1527 warningf(HERE, "'%s' is an unrecognized format function type", name);
1532 add_anchor_token(')');
1533 add_anchor_token(',');
1534 parse_constant_expression();
1535 rem_anchor_token(',');
1536 rem_anchor_token(')');
1539 add_anchor_token(')');
1540 parse_constant_expression();
1541 rem_anchor_token(')');
1545 attribute->u.value = true;
1548 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1550 if (!attribute->have_arguments)
1553 /* should have no arguments */
1554 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1555 eat_until_matching_token('(');
1556 /* we have already consumed '(', so we stop before ')', eat it */
1558 attribute->invalid = true;
1562 * Parse one GNU attribute.
1564 * Note that attribute names can be specified WITH or WITHOUT
1565 * double underscores, ie const or __const__.
1567 * The following attributes are parsed without arguments
1592 * no_instrument_function
1593 * warn_unused_result
1610 * externally_visible
1618 * The following attributes are parsed with arguments
1619 * aligned( const expression )
1620 * alias( string literal )
1621 * section( string literal )
1622 * format( identifier, const expression, const expression )
1623 * format_arg( const expression )
1624 * tls_model( string literal )
1625 * visibility( string literal )
1626 * regparm( const expression )
1627 * model( string leteral )
1628 * trap_exit( const expression )
1629 * sp_switch( string literal )
1631 * The following attributes might have arguments
1632 * weak_ref( string literal )
1633 * non_null( const expression // ',' )
1634 * interrupt( string literal )
1635 * sentinel( constant expression )
1637 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1639 gnu_attribute_t *head = *attributes;
1640 gnu_attribute_t *last = *attributes;
1641 decl_modifiers_t modifiers = 0;
1642 gnu_attribute_t *attribute;
1644 eat(T___attribute__);
1648 if (token.type != ')') {
1649 /* find the end of the list */
1651 while (last->next != NULL)
1655 /* non-empty attribute list */
1658 if (token.type == T_const) {
1660 } else if (token.type == T_volatile) {
1662 } else if (token.type == T_cdecl) {
1663 /* __attribute__((cdecl)), WITH ms mode */
1665 } else if (token.type == T_IDENTIFIER) {
1666 const symbol_t *sym = token.v.symbol;
1669 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1676 for(i = 0; i < GNU_AK_LAST; ++i) {
1677 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1680 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1683 if (kind == GNU_AK_LAST) {
1684 if (warning.attribute)
1685 warningf(HERE, "'%s' attribute directive ignored", name);
1687 /* skip possible arguments */
1688 if (token.type == '(') {
1689 eat_until_matching_token(')');
1692 /* check for arguments */
1693 attribute = allocate_gnu_attribute(kind);
1694 if (token.type == '(') {
1696 if (token.type == ')') {
1697 /* empty args are allowed */
1700 attribute->have_arguments = true;
1704 case GNU_AK_VOLATILE:
1709 case GNU_AK_NOCOMMON:
1711 case GNU_AK_NOTSHARED:
1712 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1713 case GNU_AK_WARN_UNUSED_RESULT:
1714 case GNU_AK_LONGCALL:
1715 case GNU_AK_SHORTCALL:
1716 case GNU_AK_LONG_CALL:
1717 case GNU_AK_SHORT_CALL:
1718 case GNU_AK_FUNCTION_VECTOR:
1719 case GNU_AK_INTERRUPT_HANDLER:
1720 case GNU_AK_NMI_HANDLER:
1721 case GNU_AK_NESTING:
1725 case GNU_AK_EIGTHBIT_DATA:
1726 case GNU_AK_TINY_DATA:
1727 case GNU_AK_SAVEALL:
1728 case GNU_AK_FLATTEN:
1729 case GNU_AK_SSEREGPARM:
1730 case GNU_AK_EXTERNALLY_VISIBLE:
1731 case GNU_AK_RETURN_TWICE:
1732 case GNU_AK_MAY_ALIAS:
1733 case GNU_AK_MS_STRUCT:
1734 case GNU_AK_GCC_STRUCT:
1737 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1738 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1739 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1740 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1741 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1742 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1743 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1744 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1745 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1746 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1747 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1748 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1749 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1750 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1751 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1752 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1753 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1754 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1756 case GNU_AK_ALIGNED:
1757 /* __align__ may be used without an argument */
1758 if (attribute->have_arguments) {
1759 parse_gnu_attribute_const_arg(attribute);
1763 case GNU_AK_FORMAT_ARG:
1764 case GNU_AK_REGPARM:
1765 case GNU_AK_TRAP_EXIT:
1766 if (!attribute->have_arguments) {
1767 /* should have arguments */
1768 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1769 attribute->invalid = true;
1771 parse_gnu_attribute_const_arg(attribute);
1774 case GNU_AK_SECTION:
1775 case GNU_AK_SP_SWITCH:
1776 if (!attribute->have_arguments) {
1777 /* should have arguments */
1778 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1779 attribute->invalid = true;
1781 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1784 if (!attribute->have_arguments) {
1785 /* should have arguments */
1786 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1787 attribute->invalid = true;
1789 parse_gnu_attribute_format_args(attribute);
1791 case GNU_AK_WEAKREF:
1792 /* may have one string argument */
1793 if (attribute->have_arguments)
1794 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1796 case GNU_AK_NONNULL:
1797 if (attribute->have_arguments)
1798 parse_gnu_attribute_const_arg_list(attribute);
1800 case GNU_AK_TLS_MODEL:
1801 if (!attribute->have_arguments) {
1802 /* should have arguments */
1803 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1805 parse_gnu_attribute_tls_model_arg(attribute);
1807 case GNU_AK_VISIBILITY:
1808 if (!attribute->have_arguments) {
1809 /* should have arguments */
1810 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1812 parse_gnu_attribute_visibility_arg(attribute);
1815 if (!attribute->have_arguments) {
1816 /* should have arguments */
1817 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1819 parse_gnu_attribute_model_arg(attribute);
1823 if (!attribute->have_arguments) {
1824 /* should have arguments */
1825 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1827 parse_gnu_attribute_mode_arg(attribute);
1830 case GNU_AK_INTERRUPT:
1831 /* may have one string argument */
1832 if (attribute->have_arguments)
1833 parse_gnu_attribute_interrupt_arg(attribute);
1835 case GNU_AK_SENTINEL:
1836 /* may have one string argument */
1837 if (attribute->have_arguments)
1838 parse_gnu_attribute_const_arg(attribute);
1841 /* already handled */
1845 check_no_argument(attribute, name);
1848 if (attribute != NULL) {
1850 last->next = attribute;
1853 head = last = attribute;
1857 if (token.type != ',')
1871 * Parse GNU attributes.
1873 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1875 decl_modifiers_t modifiers = 0;
1878 switch (token.type) {
1879 case T___attribute__:
1880 modifiers |= parse_gnu_attribute(attributes);
1886 if (token.type != T_STRING_LITERAL) {
1887 parse_error_expected("while parsing assembler attribute",
1888 T_STRING_LITERAL, NULL);
1889 eat_until_matching_token('(');
1892 parse_string_literals();
1897 case T_cdecl: modifiers |= DM_CDECL; break;
1898 case T__fastcall: modifiers |= DM_FASTCALL; break;
1899 case T__stdcall: modifiers |= DM_STDCALL; break;
1902 /* TODO record modifier */
1904 warningf(HERE, "Ignoring declaration modifier %K", &token);
1908 default: return modifiers;
1915 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1917 static variable_t *determine_lhs_var(expression_t *const expr,
1918 variable_t *lhs_var)
1920 switch (expr->kind) {
1921 case EXPR_REFERENCE: {
1922 entity_t *const entity = expr->reference.entity;
1923 /* we should only find variables as lavlues... */
1924 if (entity->base.kind != ENTITY_VARIABLE)
1927 return &entity->variable;
1930 case EXPR_ARRAY_ACCESS: {
1931 expression_t *const ref = expr->array_access.array_ref;
1932 variable_t * var = NULL;
1933 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1934 var = determine_lhs_var(ref, lhs_var);
1937 mark_vars_read(expr->select.compound, lhs_var);
1939 mark_vars_read(expr->array_access.index, lhs_var);
1944 if (is_type_compound(skip_typeref(expr->base.type))) {
1945 return determine_lhs_var(expr->select.compound, lhs_var);
1947 mark_vars_read(expr->select.compound, lhs_var);
1952 case EXPR_UNARY_DEREFERENCE: {
1953 expression_t *const val = expr->unary.value;
1954 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1956 return determine_lhs_var(val->unary.value, lhs_var);
1958 mark_vars_read(val, NULL);
1964 mark_vars_read(expr, NULL);
1969 #define VAR_ANY ((variable_t*)-1)
1972 * Mark declarations, which are read. This is used to deted variables, which
1976 * x is not marked as "read", because it is only read to calculate its own new
1980 * x and y are not detected as "not read", because multiple variables are
1983 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1985 switch (expr->kind) {
1986 case EXPR_REFERENCE: {
1987 entity_t *const entity = expr->reference.entity;
1988 if (entity->kind != ENTITY_VARIABLE)
1991 variable_t *variable = &entity->variable;
1992 if (lhs_var != variable && lhs_var != VAR_ANY) {
1993 variable->read = true;
1999 // TODO respect pure/const
2000 mark_vars_read(expr->call.function, NULL);
2001 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
2002 mark_vars_read(arg->expression, NULL);
2006 case EXPR_CONDITIONAL:
2007 // TODO lhs_decl should depend on whether true/false have an effect
2008 mark_vars_read(expr->conditional.condition, NULL);
2009 if (expr->conditional.true_expression != NULL)
2010 mark_vars_read(expr->conditional.true_expression, lhs_var);
2011 mark_vars_read(expr->conditional.false_expression, lhs_var);
2015 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
2017 mark_vars_read(expr->select.compound, lhs_var);
2020 case EXPR_ARRAY_ACCESS: {
2021 expression_t *const ref = expr->array_access.array_ref;
2022 mark_vars_read(ref, lhs_var);
2023 lhs_var = determine_lhs_var(ref, lhs_var);
2024 mark_vars_read(expr->array_access.index, lhs_var);
2029 mark_vars_read(expr->va_arge.ap, lhs_var);
2032 case EXPR_UNARY_CAST:
2033 /* Special case: Use void cast to mark a variable as "read" */
2034 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2039 case EXPR_UNARY_THROW:
2040 if (expr->unary.value == NULL)
2043 case EXPR_UNARY_DEREFERENCE:
2044 case EXPR_UNARY_DELETE:
2045 case EXPR_UNARY_DELETE_ARRAY:
2046 if (lhs_var == VAR_ANY)
2050 case EXPR_UNARY_NEGATE:
2051 case EXPR_UNARY_PLUS:
2052 case EXPR_UNARY_BITWISE_NEGATE:
2053 case EXPR_UNARY_NOT:
2054 case EXPR_UNARY_TAKE_ADDRESS:
2055 case EXPR_UNARY_POSTFIX_INCREMENT:
2056 case EXPR_UNARY_POSTFIX_DECREMENT:
2057 case EXPR_UNARY_PREFIX_INCREMENT:
2058 case EXPR_UNARY_PREFIX_DECREMENT:
2059 case EXPR_UNARY_CAST_IMPLICIT:
2060 case EXPR_UNARY_ASSUME:
2062 mark_vars_read(expr->unary.value, lhs_var);
2065 case EXPR_BINARY_ADD:
2066 case EXPR_BINARY_SUB:
2067 case EXPR_BINARY_MUL:
2068 case EXPR_BINARY_DIV:
2069 case EXPR_BINARY_MOD:
2070 case EXPR_BINARY_EQUAL:
2071 case EXPR_BINARY_NOTEQUAL:
2072 case EXPR_BINARY_LESS:
2073 case EXPR_BINARY_LESSEQUAL:
2074 case EXPR_BINARY_GREATER:
2075 case EXPR_BINARY_GREATEREQUAL:
2076 case EXPR_BINARY_BITWISE_AND:
2077 case EXPR_BINARY_BITWISE_OR:
2078 case EXPR_BINARY_BITWISE_XOR:
2079 case EXPR_BINARY_LOGICAL_AND:
2080 case EXPR_BINARY_LOGICAL_OR:
2081 case EXPR_BINARY_SHIFTLEFT:
2082 case EXPR_BINARY_SHIFTRIGHT:
2083 case EXPR_BINARY_COMMA:
2084 case EXPR_BINARY_ISGREATER:
2085 case EXPR_BINARY_ISGREATEREQUAL:
2086 case EXPR_BINARY_ISLESS:
2087 case EXPR_BINARY_ISLESSEQUAL:
2088 case EXPR_BINARY_ISLESSGREATER:
2089 case EXPR_BINARY_ISUNORDERED:
2090 mark_vars_read(expr->binary.left, lhs_var);
2091 mark_vars_read(expr->binary.right, lhs_var);
2094 case EXPR_BINARY_ASSIGN:
2095 case EXPR_BINARY_MUL_ASSIGN:
2096 case EXPR_BINARY_DIV_ASSIGN:
2097 case EXPR_BINARY_MOD_ASSIGN:
2098 case EXPR_BINARY_ADD_ASSIGN:
2099 case EXPR_BINARY_SUB_ASSIGN:
2100 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2101 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2102 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2103 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2104 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2105 if (lhs_var == VAR_ANY)
2107 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2108 mark_vars_read(expr->binary.right, lhs_var);
2113 determine_lhs_var(expr->va_starte.ap, lhs_var);
2119 case EXPR_CHARACTER_CONSTANT:
2120 case EXPR_WIDE_CHARACTER_CONSTANT:
2121 case EXPR_STRING_LITERAL:
2122 case EXPR_WIDE_STRING_LITERAL:
2123 case EXPR_COMPOUND_LITERAL: // TODO init?
2125 case EXPR_CLASSIFY_TYPE:
2128 case EXPR_BUILTIN_SYMBOL:
2129 case EXPR_BUILTIN_CONSTANT_P:
2130 case EXPR_BUILTIN_PREFETCH:
2132 case EXPR_STATEMENT: // TODO
2133 case EXPR_LABEL_ADDRESS:
2134 case EXPR_BINARY_BUILTIN_EXPECT:
2135 case EXPR_REFERENCE_ENUM_VALUE:
2139 panic("unhandled expression");
2142 static designator_t *parse_designation(void)
2144 designator_t *result = NULL;
2145 designator_t *last = NULL;
2148 designator_t *designator;
2149 switch (token.type) {
2151 designator = allocate_ast_zero(sizeof(designator[0]));
2152 designator->source_position = token.source_position;
2154 add_anchor_token(']');
2155 designator->array_index = parse_constant_expression();
2156 rem_anchor_token(']');
2160 designator = allocate_ast_zero(sizeof(designator[0]));
2161 designator->source_position = token.source_position;
2163 if (token.type != T_IDENTIFIER) {
2164 parse_error_expected("while parsing designator",
2165 T_IDENTIFIER, NULL);
2168 designator->symbol = token.v.symbol;
2176 assert(designator != NULL);
2178 last->next = designator;
2180 result = designator;
2188 static initializer_t *initializer_from_string(array_type_t *type,
2189 const string_t *const string)
2191 /* TODO: check len vs. size of array type */
2194 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2195 initializer->string.string = *string;
2200 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2201 wide_string_t *const string)
2203 /* TODO: check len vs. size of array type */
2206 initializer_t *const initializer =
2207 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2208 initializer->wide_string.string = *string;
2214 * Build an initializer from a given expression.
2216 static initializer_t *initializer_from_expression(type_t *orig_type,
2217 expression_t *expression)
2219 /* TODO check that expression is a constant expression */
2221 /* § 6.7.8.14/15 char array may be initialized by string literals */
2222 type_t *type = skip_typeref(orig_type);
2223 type_t *expr_type_orig = expression->base.type;
2224 type_t *expr_type = skip_typeref(expr_type_orig);
2225 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2226 array_type_t *const array_type = &type->array;
2227 type_t *const element_type = skip_typeref(array_type->element_type);
2229 if (element_type->kind == TYPE_ATOMIC) {
2230 atomic_type_kind_t akind = element_type->atomic.akind;
2231 switch (expression->kind) {
2232 case EXPR_STRING_LITERAL:
2233 if (akind == ATOMIC_TYPE_CHAR
2234 || akind == ATOMIC_TYPE_SCHAR
2235 || akind == ATOMIC_TYPE_UCHAR) {
2236 return initializer_from_string(array_type,
2237 &expression->string.value);
2240 case EXPR_WIDE_STRING_LITERAL: {
2241 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2242 if (get_unqualified_type(element_type) == bare_wchar_type) {
2243 return initializer_from_wide_string(array_type,
2244 &expression->wide_string.value);
2254 assign_error_t error = semantic_assign(type, expression);
2255 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2257 report_assign_error(error, type, expression, "initializer",
2258 &expression->base.source_position);
2260 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2262 if (type->kind == TYPE_BITFIELD) {
2263 type = type->bitfield.base_type;
2266 result->value.value = create_implicit_cast(expression, type);
2272 * Checks if a given expression can be used as an constant initializer.
2274 static bool is_initializer_constant(const expression_t *expression)
2276 return is_constant_expression(expression)
2277 || is_address_constant(expression);
2281 * Parses an scalar initializer.
2283 * § 6.7.8.11; eat {} without warning
2285 static initializer_t *parse_scalar_initializer(type_t *type,
2286 bool must_be_constant)
2288 /* there might be extra {} hierarchies */
2290 if (token.type == '{') {
2292 warningf(HERE, "extra curly braces around scalar initializer");
2296 } while (token.type == '{');
2299 expression_t *expression = parse_assignment_expression();
2300 mark_vars_read(expression, NULL);
2301 if (must_be_constant && !is_initializer_constant(expression)) {
2302 errorf(&expression->base.source_position,
2303 "Initialisation expression '%E' is not constant\n",
2307 initializer_t *initializer = initializer_from_expression(type, expression);
2309 if (initializer == NULL) {
2310 errorf(&expression->base.source_position,
2311 "expression '%E' (type '%T') doesn't match expected type '%T'",
2312 expression, expression->base.type, type);
2317 bool additional_warning_displayed = false;
2318 while (braces > 0) {
2319 if (token.type == ',') {
2322 if (token.type != '}') {
2323 if (!additional_warning_displayed && warning.other) {
2324 warningf(HERE, "additional elements in scalar initializer");
2325 additional_warning_displayed = true;
2336 * An entry in the type path.
2338 typedef struct type_path_entry_t type_path_entry_t;
2339 struct type_path_entry_t {
2340 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2342 size_t index; /**< For array types: the current index. */
2343 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2348 * A type path expression a position inside compound or array types.
2350 typedef struct type_path_t type_path_t;
2351 struct type_path_t {
2352 type_path_entry_t *path; /**< An flexible array containing the current path. */
2353 type_t *top_type; /**< type of the element the path points */
2354 size_t max_index; /**< largest index in outermost array */
2358 * Prints a type path for debugging.
2360 static __attribute__((unused)) void debug_print_type_path(
2361 const type_path_t *path)
2363 size_t len = ARR_LEN(path->path);
2365 for(size_t i = 0; i < len; ++i) {
2366 const type_path_entry_t *entry = & path->path[i];
2368 type_t *type = skip_typeref(entry->type);
2369 if (is_type_compound(type)) {
2370 /* in gcc mode structs can have no members */
2371 if (entry->v.compound_entry == NULL) {
2375 fprintf(stderr, ".%s",
2376 entry->v.compound_entry->base.symbol->string);
2377 } else if (is_type_array(type)) {
2378 fprintf(stderr, "[%zu]", entry->v.index);
2380 fprintf(stderr, "-INVALID-");
2383 if (path->top_type != NULL) {
2384 fprintf(stderr, " (");
2385 print_type(path->top_type);
2386 fprintf(stderr, ")");
2391 * Return the top type path entry, ie. in a path
2392 * (type).a.b returns the b.
2394 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2396 size_t len = ARR_LEN(path->path);
2398 return &path->path[len-1];
2402 * Enlarge the type path by an (empty) element.
2404 static type_path_entry_t *append_to_type_path(type_path_t *path)
2406 size_t len = ARR_LEN(path->path);
2407 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2409 type_path_entry_t *result = & path->path[len];
2410 memset(result, 0, sizeof(result[0]));
2415 * Descending into a sub-type. Enter the scope of the current top_type.
2417 static void descend_into_subtype(type_path_t *path)
2419 type_t *orig_top_type = path->top_type;
2420 type_t *top_type = skip_typeref(orig_top_type);
2422 type_path_entry_t *top = append_to_type_path(path);
2423 top->type = top_type;
2425 if (is_type_compound(top_type)) {
2426 compound_t *compound = top_type->compound.compound;
2427 entity_t *entry = compound->members.entities;
2429 if (entry != NULL) {
2430 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2431 top->v.compound_entry = &entry->declaration;
2432 path->top_type = entry->declaration.type;
2434 path->top_type = NULL;
2436 } else if (is_type_array(top_type)) {
2438 path->top_type = top_type->array.element_type;
2440 assert(!is_type_valid(top_type));
2445 * Pop an entry from the given type path, ie. returning from
2446 * (type).a.b to (type).a
2448 static void ascend_from_subtype(type_path_t *path)
2450 type_path_entry_t *top = get_type_path_top(path);
2452 path->top_type = top->type;
2454 size_t len = ARR_LEN(path->path);
2455 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2459 * Pop entries from the given type path until the given
2460 * path level is reached.
2462 static void ascend_to(type_path_t *path, size_t top_path_level)
2464 size_t len = ARR_LEN(path->path);
2466 while (len > top_path_level) {
2467 ascend_from_subtype(path);
2468 len = ARR_LEN(path->path);
2472 static bool walk_designator(type_path_t *path, const designator_t *designator,
2473 bool used_in_offsetof)
2475 for( ; designator != NULL; designator = designator->next) {
2476 type_path_entry_t *top = get_type_path_top(path);
2477 type_t *orig_type = top->type;
2479 type_t *type = skip_typeref(orig_type);
2481 if (designator->symbol != NULL) {
2482 symbol_t *symbol = designator->symbol;
2483 if (!is_type_compound(type)) {
2484 if (is_type_valid(type)) {
2485 errorf(&designator->source_position,
2486 "'.%Y' designator used for non-compound type '%T'",
2490 top->type = type_error_type;
2491 top->v.compound_entry = NULL;
2492 orig_type = type_error_type;
2494 compound_t *compound = type->compound.compound;
2495 entity_t *iter = compound->members.entities;
2496 for( ; iter != NULL; iter = iter->base.next) {
2497 if (iter->base.symbol == symbol) {
2502 errorf(&designator->source_position,
2503 "'%T' has no member named '%Y'", orig_type, symbol);
2506 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2507 if (used_in_offsetof) {
2508 type_t *real_type = skip_typeref(iter->declaration.type);
2509 if (real_type->kind == TYPE_BITFIELD) {
2510 errorf(&designator->source_position,
2511 "offsetof designator '%Y' may not specify bitfield",
2517 top->type = orig_type;
2518 top->v.compound_entry = &iter->declaration;
2519 orig_type = iter->declaration.type;
2522 expression_t *array_index = designator->array_index;
2523 assert(designator->array_index != NULL);
2525 if (!is_type_array(type)) {
2526 if (is_type_valid(type)) {
2527 errorf(&designator->source_position,
2528 "[%E] designator used for non-array type '%T'",
2529 array_index, orig_type);
2534 long index = fold_constant(array_index);
2535 if (!used_in_offsetof) {
2537 errorf(&designator->source_position,
2538 "array index [%E] must be positive", array_index);
2539 } else if (type->array.size_constant) {
2540 long array_size = type->array.size;
2541 if (index >= array_size) {
2542 errorf(&designator->source_position,
2543 "designator [%E] (%d) exceeds array size %d",
2544 array_index, index, array_size);
2549 top->type = orig_type;
2550 top->v.index = (size_t) index;
2551 orig_type = type->array.element_type;
2553 path->top_type = orig_type;
2555 if (designator->next != NULL) {
2556 descend_into_subtype(path);
2565 static void advance_current_object(type_path_t *path, size_t top_path_level)
2567 type_path_entry_t *top = get_type_path_top(path);
2569 type_t *type = skip_typeref(top->type);
2570 if (is_type_union(type)) {
2571 /* in unions only the first element is initialized */
2572 top->v.compound_entry = NULL;
2573 } else if (is_type_struct(type)) {
2574 declaration_t *entry = top->v.compound_entry;
2576 entity_t *next_entity = entry->base.next;
2577 if (next_entity != NULL) {
2578 assert(is_declaration(next_entity));
2579 entry = &next_entity->declaration;
2584 top->v.compound_entry = entry;
2585 if (entry != NULL) {
2586 path->top_type = entry->type;
2589 } else if (is_type_array(type)) {
2590 assert(is_type_array(type));
2594 if (!type->array.size_constant || top->v.index < type->array.size) {
2598 assert(!is_type_valid(type));
2602 /* we're past the last member of the current sub-aggregate, try if we
2603 * can ascend in the type hierarchy and continue with another subobject */
2604 size_t len = ARR_LEN(path->path);
2606 if (len > top_path_level) {
2607 ascend_from_subtype(path);
2608 advance_current_object(path, top_path_level);
2610 path->top_type = NULL;
2615 * skip until token is found.
2617 static void skip_until(int type)
2619 while (token.type != type) {
2620 if (token.type == T_EOF)
2627 * skip any {...} blocks until a closing bracket is reached.
2629 static void skip_initializers(void)
2631 if (token.type == '{')
2634 while (token.type != '}') {
2635 if (token.type == T_EOF)
2637 if (token.type == '{') {
2645 static initializer_t *create_empty_initializer(void)
2647 static initializer_t empty_initializer
2648 = { .list = { { INITIALIZER_LIST }, 0 } };
2649 return &empty_initializer;
2653 * Parse a part of an initialiser for a struct or union,
2655 static initializer_t *parse_sub_initializer(type_path_t *path,
2656 type_t *outer_type, size_t top_path_level,
2657 parse_initializer_env_t *env)
2659 if (token.type == '}') {
2660 /* empty initializer */
2661 return create_empty_initializer();
2664 type_t *orig_type = path->top_type;
2665 type_t *type = NULL;
2667 if (orig_type == NULL) {
2668 /* We are initializing an empty compound. */
2670 type = skip_typeref(orig_type);
2673 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2676 designator_t *designator = NULL;
2677 if (token.type == '.' || token.type == '[') {
2678 designator = parse_designation();
2679 goto finish_designator;
2680 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2681 /* GNU-style designator ("identifier: value") */
2682 designator = allocate_ast_zero(sizeof(designator[0]));
2683 designator->source_position = token.source_position;
2684 designator->symbol = token.v.symbol;
2689 /* reset path to toplevel, evaluate designator from there */
2690 ascend_to(path, top_path_level);
2691 if (!walk_designator(path, designator, false)) {
2692 /* can't continue after designation error */
2696 initializer_t *designator_initializer
2697 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2698 designator_initializer->designator.designator = designator;
2699 ARR_APP1(initializer_t*, initializers, designator_initializer);
2701 orig_type = path->top_type;
2702 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2707 if (token.type == '{') {
2708 if (type != NULL && is_type_scalar(type)) {
2709 sub = parse_scalar_initializer(type, env->must_be_constant);
2713 if (env->entity != NULL) {
2715 "extra brace group at end of initializer for '%Y'",
2716 env->entity->base.symbol);
2718 errorf(HERE, "extra brace group at end of initializer");
2721 descend_into_subtype(path);
2723 add_anchor_token('}');
2724 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2726 rem_anchor_token('}');
2729 ascend_from_subtype(path);
2733 goto error_parse_next;
2737 /* must be an expression */
2738 expression_t *expression = parse_assignment_expression();
2740 if (env->must_be_constant && !is_initializer_constant(expression)) {
2741 errorf(&expression->base.source_position,
2742 "Initialisation expression '%E' is not constant\n",
2747 /* we are already outside, ... */
2748 type_t *const outer_type_skip = skip_typeref(outer_type);
2749 if (is_type_compound(outer_type_skip) &&
2750 !outer_type_skip->compound.compound->complete) {
2751 goto error_parse_next;
2756 /* handle { "string" } special case */
2757 if ((expression->kind == EXPR_STRING_LITERAL
2758 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2759 && outer_type != NULL) {
2760 sub = initializer_from_expression(outer_type, expression);
2762 if (token.type == ',') {
2765 if (token.type != '}' && warning.other) {
2766 warningf(HERE, "excessive elements in initializer for type '%T'",
2769 /* TODO: eat , ... */
2774 /* descend into subtypes until expression matches type */
2776 orig_type = path->top_type;
2777 type = skip_typeref(orig_type);
2779 sub = initializer_from_expression(orig_type, expression);
2783 if (!is_type_valid(type)) {
2786 if (is_type_scalar(type)) {
2787 errorf(&expression->base.source_position,
2788 "expression '%E' doesn't match expected type '%T'",
2789 expression, orig_type);
2793 descend_into_subtype(path);
2797 /* update largest index of top array */
2798 const type_path_entry_t *first = &path->path[0];
2799 type_t *first_type = first->type;
2800 first_type = skip_typeref(first_type);
2801 if (is_type_array(first_type)) {
2802 size_t index = first->v.index;
2803 if (index > path->max_index)
2804 path->max_index = index;
2808 /* append to initializers list */
2809 ARR_APP1(initializer_t*, initializers, sub);
2812 if (warning.other) {
2813 if (env->entity != NULL) {
2814 warningf(HERE, "excess elements in struct initializer for '%Y'",
2815 env->entity->base.symbol);
2817 warningf(HERE, "excess elements in struct initializer");
2823 if (token.type == '}') {
2827 if (token.type == '}') {
2832 /* advance to the next declaration if we are not at the end */
2833 advance_current_object(path, top_path_level);
2834 orig_type = path->top_type;
2835 if (orig_type != NULL)
2836 type = skip_typeref(orig_type);
2842 size_t len = ARR_LEN(initializers);
2843 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2844 initializer_t *result = allocate_ast_zero(size);
2845 result->kind = INITIALIZER_LIST;
2846 result->list.len = len;
2847 memcpy(&result->list.initializers, initializers,
2848 len * sizeof(initializers[0]));
2850 DEL_ARR_F(initializers);
2851 ascend_to(path, top_path_level+1);
2856 skip_initializers();
2857 DEL_ARR_F(initializers);
2858 ascend_to(path, top_path_level+1);
2863 * Parses an initializer. Parsers either a compound literal
2864 * (env->declaration == NULL) or an initializer of a declaration.
2866 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2868 type_t *type = skip_typeref(env->type);
2869 initializer_t *result = NULL;
2872 if (is_type_scalar(type)) {
2873 result = parse_scalar_initializer(type, env->must_be_constant);
2874 } else if (token.type == '{') {
2878 memset(&path, 0, sizeof(path));
2879 path.top_type = env->type;
2880 path.path = NEW_ARR_F(type_path_entry_t, 0);
2882 descend_into_subtype(&path);
2884 add_anchor_token('}');
2885 result = parse_sub_initializer(&path, env->type, 1, env);
2886 rem_anchor_token('}');
2888 max_index = path.max_index;
2889 DEL_ARR_F(path.path);
2893 /* parse_scalar_initializer() also works in this case: we simply
2894 * have an expression without {} around it */
2895 result = parse_scalar_initializer(type, env->must_be_constant);
2898 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2899 * the array type size */
2900 if (is_type_array(type) && type->array.size_expression == NULL
2901 && result != NULL) {
2903 switch (result->kind) {
2904 case INITIALIZER_LIST:
2905 size = max_index + 1;
2908 case INITIALIZER_STRING:
2909 size = result->string.string.size;
2912 case INITIALIZER_WIDE_STRING:
2913 size = result->wide_string.string.size;
2916 case INITIALIZER_DESIGNATOR:
2917 case INITIALIZER_VALUE:
2918 /* can happen for parse errors */
2923 internal_errorf(HERE, "invalid initializer type");
2926 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2927 cnst->base.type = type_size_t;
2928 cnst->conste.v.int_value = size;
2930 type_t *new_type = duplicate_type(type);
2932 new_type->array.size_expression = cnst;
2933 new_type->array.size_constant = true;
2934 new_type->array.has_implicit_size = true;
2935 new_type->array.size = size;
2936 env->type = new_type;
2944 static void append_entity(scope_t *scope, entity_t *entity)
2946 if (scope->last_entity != NULL) {
2947 scope->last_entity->base.next = entity;
2949 scope->entities = entity;
2951 scope->last_entity = entity;
2955 static compound_t *parse_compound_type_specifier(bool is_struct)
2957 gnu_attribute_t *attributes = NULL;
2958 decl_modifiers_t modifiers = 0;
2965 symbol_t *symbol = NULL;
2966 compound_t *compound = NULL;
2968 if (token.type == T___attribute__) {
2969 modifiers |= parse_attributes(&attributes);
2972 if (token.type == T_IDENTIFIER) {
2973 symbol = token.v.symbol;
2976 namespace_t const namespc =
2977 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2978 entity_t *entity = get_entity(symbol, namespc);
2979 if (entity != NULL) {
2980 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2981 compound = &entity->compound;
2982 if (compound->base.parent_scope != scope &&
2983 (token.type == '{' || token.type == ';')) {
2984 /* we're in an inner scope and have a definition. Override
2985 existing definition in outer scope */
2987 } else if (compound->complete && token.type == '{') {
2988 assert(symbol != NULL);
2989 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2990 is_struct ? "struct" : "union", symbol,
2991 &compound->base.source_position);
2992 /* clear members in the hope to avoid further errors */
2993 compound->members.entities = NULL;
2996 } else if (token.type != '{') {
2998 parse_error_expected("while parsing struct type specifier",
2999 T_IDENTIFIER, '{', NULL);
3001 parse_error_expected("while parsing union type specifier",
3002 T_IDENTIFIER, '{', NULL);
3008 if (compound == NULL) {
3009 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
3010 entity_t *entity = allocate_entity_zero(kind);
3011 compound = &entity->compound;
3013 compound->base.namespc =
3014 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
3015 compound->base.source_position = token.source_position;
3016 compound->base.symbol = symbol;
3017 compound->base.parent_scope = scope;
3018 if (symbol != NULL) {
3019 environment_push(entity);
3021 append_entity(scope, entity);
3024 if (token.type == '{') {
3025 compound->complete = true;
3027 parse_compound_type_entries(compound);
3028 modifiers |= parse_attributes(&attributes);
3031 compound->modifiers |= modifiers;
3035 static void parse_enum_entries(type_t *const enum_type)
3039 if (token.type == '}') {
3041 errorf(HERE, "empty enum not allowed");
3045 add_anchor_token('}');
3047 if (token.type != T_IDENTIFIER) {
3048 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3050 rem_anchor_token('}');
3054 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3055 entity->enum_value.enum_type = enum_type;
3056 entity->base.symbol = token.v.symbol;
3057 entity->base.source_position = token.source_position;
3060 if (token.type == '=') {
3062 expression_t *value = parse_constant_expression();
3064 value = create_implicit_cast(value, enum_type);
3065 entity->enum_value.value = value;
3070 record_entity(entity, false);
3072 if (token.type != ',')
3075 } while (token.type != '}');
3076 rem_anchor_token('}');
3084 static type_t *parse_enum_specifier(void)
3086 gnu_attribute_t *attributes = NULL;
3091 if (token.type == T_IDENTIFIER) {
3092 symbol = token.v.symbol;
3095 entity = get_entity(symbol, NAMESPACE_ENUM);
3096 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3097 } else if (token.type != '{') {
3098 parse_error_expected("while parsing enum type specifier",
3099 T_IDENTIFIER, '{', NULL);
3106 if (entity == NULL) {
3107 entity = allocate_entity_zero(ENTITY_ENUM);
3108 entity->base.namespc = NAMESPACE_ENUM;
3109 entity->base.source_position = token.source_position;
3110 entity->base.symbol = symbol;
3111 entity->base.parent_scope = scope;
3114 type_t *const type = allocate_type_zero(TYPE_ENUM);
3115 type->enumt.enume = &entity->enume;
3117 if (token.type == '{') {
3118 if (entity->enume.complete) {
3119 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3120 symbol, &entity->base.source_position);
3122 if (symbol != NULL) {
3123 environment_push(entity);
3125 append_entity(scope, entity);
3126 entity->enume.complete = true;
3128 parse_enum_entries(type);
3129 parse_attributes(&attributes);
3130 } else if(!entity->enume.complete && !(c_mode & _GNUC)) {
3131 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3139 * if a symbol is a typedef to another type, return true
3141 static bool is_typedef_symbol(symbol_t *symbol)
3143 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3144 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3147 static type_t *parse_typeof(void)
3154 add_anchor_token(')');
3156 expression_t *expression = NULL;
3158 bool old_type_prop = in_type_prop;
3159 bool old_gcc_extension = in_gcc_extension;
3160 in_type_prop = true;
3162 while (token.type == T___extension__) {
3163 /* This can be a prefix to a typename or an expression. */
3165 in_gcc_extension = true;
3167 switch (token.type) {
3169 if (is_typedef_symbol(token.v.symbol)) {
3170 type = parse_typename();
3172 expression = parse_expression();
3173 type = expression->base.type;
3178 type = parse_typename();
3182 expression = parse_expression();
3183 type = expression->base.type;
3186 in_type_prop = old_type_prop;
3187 in_gcc_extension = old_gcc_extension;
3189 rem_anchor_token(')');
3192 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3193 typeof_type->typeoft.expression = expression;
3194 typeof_type->typeoft.typeof_type = type;
3201 typedef enum specifiers_t {
3202 SPECIFIER_SIGNED = 1 << 0,
3203 SPECIFIER_UNSIGNED = 1 << 1,
3204 SPECIFIER_LONG = 1 << 2,
3205 SPECIFIER_INT = 1 << 3,
3206 SPECIFIER_DOUBLE = 1 << 4,
3207 SPECIFIER_CHAR = 1 << 5,
3208 SPECIFIER_SHORT = 1 << 6,
3209 SPECIFIER_LONG_LONG = 1 << 7,
3210 SPECIFIER_FLOAT = 1 << 8,
3211 SPECIFIER_BOOL = 1 << 9,
3212 SPECIFIER_VOID = 1 << 10,
3213 SPECIFIER_INT8 = 1 << 11,
3214 SPECIFIER_INT16 = 1 << 12,
3215 SPECIFIER_INT32 = 1 << 13,
3216 SPECIFIER_INT64 = 1 << 14,
3217 SPECIFIER_INT128 = 1 << 15,
3218 SPECIFIER_COMPLEX = 1 << 16,
3219 SPECIFIER_IMAGINARY = 1 << 17,
3222 static type_t *create_builtin_type(symbol_t *const symbol,
3223 type_t *const real_type)
3225 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3226 type->builtin.symbol = symbol;
3227 type->builtin.real_type = real_type;
3229 type_t *result = typehash_insert(type);
3230 if (type != result) {
3237 static type_t *get_typedef_type(symbol_t *symbol)
3239 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3240 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3243 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3244 type->typedeft.typedefe = &entity->typedefe;
3250 * check for the allowed MS alignment values.
3252 static bool check_alignment_value(long long intvalue)
3254 if (intvalue < 1 || intvalue > 8192) {
3255 errorf(HERE, "illegal alignment value");
3258 unsigned v = (unsigned)intvalue;
3259 for (unsigned i = 1; i <= 8192; i += i) {
3263 errorf(HERE, "alignment must be power of two");
3267 #define DET_MOD(name, tag) do { \
3268 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3269 *modifiers |= tag; \
3272 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3274 decl_modifiers_t *modifiers = &specifiers->modifiers;
3277 if (token.type == T_restrict) {
3279 DET_MOD(restrict, DM_RESTRICT);
3281 } else if (token.type != T_IDENTIFIER)
3283 symbol_t *symbol = token.v.symbol;
3284 if (symbol == sym_align) {
3287 if (token.type != T_INTEGER)
3289 if (check_alignment_value(token.v.intvalue)) {
3290 if (specifiers->alignment != 0 && warning.other)
3291 warningf(HERE, "align used more than once");
3292 specifiers->alignment = (unsigned char)token.v.intvalue;
3296 } else if (symbol == sym_allocate) {
3299 if (token.type != T_IDENTIFIER)
3301 (void)token.v.symbol;
3303 } else if (symbol == sym_dllimport) {
3305 DET_MOD(dllimport, DM_DLLIMPORT);
3306 } else if (symbol == sym_dllexport) {
3308 DET_MOD(dllexport, DM_DLLEXPORT);
3309 } else if (symbol == sym_thread) {
3311 DET_MOD(thread, DM_THREAD);
3312 } else if (symbol == sym_naked) {
3314 DET_MOD(naked, DM_NAKED);
3315 } else if (symbol == sym_noinline) {
3317 DET_MOD(noinline, DM_NOINLINE);
3318 } else if (symbol == sym_noreturn) {
3320 DET_MOD(noreturn, DM_NORETURN);
3321 } else if (symbol == sym_nothrow) {
3323 DET_MOD(nothrow, DM_NOTHROW);
3324 } else if (symbol == sym_novtable) {
3326 DET_MOD(novtable, DM_NOVTABLE);
3327 } else if (symbol == sym_property) {
3331 bool is_get = false;
3332 if (token.type != T_IDENTIFIER)
3334 if (token.v.symbol == sym_get) {
3336 } else if (token.v.symbol == sym_put) {
3338 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3343 if (token.type != T_IDENTIFIER)
3346 if (specifiers->get_property_sym != NULL) {
3347 errorf(HERE, "get property name already specified");
3349 specifiers->get_property_sym = token.v.symbol;
3352 if (specifiers->put_property_sym != NULL) {
3353 errorf(HERE, "put property name already specified");
3355 specifiers->put_property_sym = token.v.symbol;
3359 if (token.type == ',') {
3366 } else if (symbol == sym_selectany) {
3368 DET_MOD(selectany, DM_SELECTANY);
3369 } else if (symbol == sym_uuid) {
3372 if (token.type != T_STRING_LITERAL)
3376 } else if (symbol == sym_deprecated) {
3378 if (specifiers->deprecated != 0 && warning.other)
3379 warningf(HERE, "deprecated used more than once");
3380 specifiers->deprecated = true;
3381 if (token.type == '(') {
3383 if (token.type == T_STRING_LITERAL) {
3384 specifiers->deprecated_string = token.v.string.begin;
3387 errorf(HERE, "string literal expected");
3391 } else if (symbol == sym_noalias) {
3393 DET_MOD(noalias, DM_NOALIAS);
3396 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3398 if (token.type == '(')
3402 if (token.type == ',')
3409 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3411 entity_t *entity = allocate_entity_zero(kind);
3412 entity->base.source_position = *HERE;
3413 entity->base.symbol = symbol;
3414 if (is_declaration(entity)) {
3415 entity->declaration.type = type_error_type;
3416 entity->declaration.implicit = true;
3417 } else if (kind == ENTITY_TYPEDEF) {
3418 entity->typedefe.type = type_error_type;
3420 record_entity(entity, false);
3425 * Finish the construction of a struct type by calculating
3426 * its size, offsets, alignment.
3428 static void finish_struct_type(compound_type_t *type)
3430 assert(type->compound != NULL);
3432 compound_t *compound = type->compound;
3433 if (!compound->complete)
3438 il_alignment_t alignment = 1;
3439 bool need_pad = false;
3441 entity_t *entry = compound->members.entities;
3442 for (; entry != NULL; entry = entry->base.next) {
3443 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3446 type_t *m_type = skip_typeref(entry->declaration.type);
3447 if (! is_type_valid(m_type)) {
3448 /* simply ignore errors here */
3451 il_alignment_t m_alignment = m_type->base.alignment;
3452 if (m_alignment > alignment)
3453 alignment = m_alignment;
3455 offset = (size + m_alignment - 1) & -m_alignment;
3459 entry->compound_member.offset = offset;
3460 size = offset + m_type->base.size;
3462 if (type->base.alignment != 0) {
3463 alignment = type->base.alignment;
3466 offset = (size + alignment - 1) & -alignment;
3470 if (warning.padded && need_pad) {
3471 warningf(&compound->base.source_position,
3472 "'%#T' needs padding", type, compound->base.symbol);
3474 if (warning.packed && !need_pad) {
3475 warningf(&compound->base.source_position,
3476 "superfluous packed attribute on '%#T'",
3477 type, compound->base.symbol);
3480 type->base.size = offset;
3481 type->base.alignment = alignment;
3485 * Finish the construction of an union type by calculating
3486 * its size and alignment.
3488 static void finish_union_type(compound_type_t *type)
3490 assert(type->compound != NULL);
3492 compound_t *compound = type->compound;
3493 if (! compound->complete)
3497 il_alignment_t alignment = 1;
3499 entity_t *entry = compound->members.entities;
3500 for (; entry != NULL; entry = entry->base.next) {
3501 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3504 type_t *m_type = skip_typeref(entry->declaration.type);
3505 if (! is_type_valid(m_type))
3508 entry->compound_member.offset = 0;
3509 if (m_type->base.size > size)
3510 size = m_type->base.size;
3511 if (m_type->base.alignment > alignment)
3512 alignment = m_type->base.alignment;
3514 if (type->base.alignment != 0) {
3515 alignment = type->base.alignment;
3517 size = (size + alignment - 1) & -alignment;
3518 type->base.size = size;
3519 type->base.alignment = alignment;
3522 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3524 type_t *type = NULL;
3525 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3526 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3527 unsigned type_specifiers = 0;
3528 bool newtype = false;
3529 bool saw_error = false;
3530 bool old_gcc_extension = in_gcc_extension;
3532 specifiers->source_position = token.source_position;
3535 specifiers->modifiers
3536 |= parse_attributes(&specifiers->gnu_attributes);
3537 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3538 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3540 switch (token.type) {
3543 #define MATCH_STORAGE_CLASS(token, class) \
3545 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3546 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3548 specifiers->storage_class = class; \
3552 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3553 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3554 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3555 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3556 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3561 add_anchor_token(')');
3562 parse_microsoft_extended_decl_modifier(specifiers);
3563 rem_anchor_token(')');
3568 switch (specifiers->storage_class) {
3569 case STORAGE_CLASS_NONE:
3570 specifiers->storage_class = STORAGE_CLASS_THREAD;
3573 case STORAGE_CLASS_EXTERN:
3574 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3577 case STORAGE_CLASS_STATIC:
3578 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3582 errorf(HERE, "multiple storage classes in declaration specifiers");
3588 /* type qualifiers */
3589 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3591 qualifiers |= qualifier; \
3595 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3596 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3597 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3598 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3599 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3600 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3601 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3602 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3604 case T___extension__:
3606 in_gcc_extension = true;
3609 /* type specifiers */
3610 #define MATCH_SPECIFIER(token, specifier, name) \
3613 if (type_specifiers & specifier) { \
3614 errorf(HERE, "multiple " name " type specifiers given"); \
3616 type_specifiers |= specifier; \
3620 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3621 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3622 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3623 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3624 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3625 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3626 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3627 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3628 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3629 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3630 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3631 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3632 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3633 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3634 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3635 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3636 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3638 case T__forceinline:
3639 /* only in microsoft mode */
3640 specifiers->modifiers |= DM_FORCEINLINE;
3645 specifiers->is_inline = true;
3650 if (type_specifiers & SPECIFIER_LONG_LONG) {
3651 errorf(HERE, "multiple type specifiers given");
3652 } else if (type_specifiers & SPECIFIER_LONG) {
3653 type_specifiers |= SPECIFIER_LONG_LONG;
3655 type_specifiers |= SPECIFIER_LONG;
3660 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3662 type->compound.compound = parse_compound_type_specifier(true);
3663 finish_struct_type(&type->compound);
3667 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3668 type->compound.compound = parse_compound_type_specifier(false);
3669 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3670 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3671 finish_union_type(&type->compound);
3675 type = parse_enum_specifier();
3678 type = parse_typeof();
3680 case T___builtin_va_list:
3681 type = duplicate_type(type_valist);
3685 case T_IDENTIFIER: {
3686 /* only parse identifier if we haven't found a type yet */
3687 if (type != NULL || type_specifiers != 0) {
3688 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3689 * declaration, so it doesn't generate errors about expecting '(' or
3691 switch (look_ahead(1)->type) {
3698 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3701 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3706 goto finish_specifiers;
3710 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3711 if (typedef_type == NULL) {
3712 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3713 * declaration, so it doesn't generate 'implicit int' followed by more
3714 * errors later on. */
3715 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3720 errorf(HERE, "%K does not name a type", &token);
3723 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3725 type = allocate_type_zero(TYPE_TYPEDEF);
3726 type->typedeft.typedefe = &entity->typedefe;
3730 if (la1_type == '*')
3731 goto finish_specifiers;
3736 goto finish_specifiers;
3741 type = typedef_type;
3745 /* function specifier */
3747 goto finish_specifiers;
3752 in_gcc_extension = old_gcc_extension;
3754 if (type == NULL || (saw_error && type_specifiers != 0)) {
3755 atomic_type_kind_t atomic_type;
3757 /* match valid basic types */
3758 switch (type_specifiers) {
3759 case SPECIFIER_VOID:
3760 atomic_type = ATOMIC_TYPE_VOID;
3762 case SPECIFIER_CHAR:
3763 atomic_type = ATOMIC_TYPE_CHAR;
3765 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3766 atomic_type = ATOMIC_TYPE_SCHAR;
3768 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3769 atomic_type = ATOMIC_TYPE_UCHAR;
3771 case SPECIFIER_SHORT:
3772 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3773 case SPECIFIER_SHORT | SPECIFIER_INT:
3774 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3775 atomic_type = ATOMIC_TYPE_SHORT;
3777 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3778 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3779 atomic_type = ATOMIC_TYPE_USHORT;
3782 case SPECIFIER_SIGNED:
3783 case SPECIFIER_SIGNED | SPECIFIER_INT:
3784 atomic_type = ATOMIC_TYPE_INT;
3786 case SPECIFIER_UNSIGNED:
3787 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3788 atomic_type = ATOMIC_TYPE_UINT;
3790 case SPECIFIER_LONG:
3791 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3792 case SPECIFIER_LONG | SPECIFIER_INT:
3793 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3794 atomic_type = ATOMIC_TYPE_LONG;
3796 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3797 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3798 atomic_type = ATOMIC_TYPE_ULONG;
3801 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3802 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3803 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3804 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3806 atomic_type = ATOMIC_TYPE_LONGLONG;
3807 goto warn_about_long_long;
3809 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3810 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3812 atomic_type = ATOMIC_TYPE_ULONGLONG;
3813 warn_about_long_long:
3814 if (warning.long_long) {
3815 warningf(&specifiers->source_position,
3816 "ISO C90 does not support 'long long'");
3820 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3821 atomic_type = unsigned_int8_type_kind;
3824 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3825 atomic_type = unsigned_int16_type_kind;
3828 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3829 atomic_type = unsigned_int32_type_kind;
3832 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3833 atomic_type = unsigned_int64_type_kind;
3836 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3837 atomic_type = unsigned_int128_type_kind;
3840 case SPECIFIER_INT8:
3841 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3842 atomic_type = int8_type_kind;
3845 case SPECIFIER_INT16:
3846 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3847 atomic_type = int16_type_kind;
3850 case SPECIFIER_INT32:
3851 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3852 atomic_type = int32_type_kind;
3855 case SPECIFIER_INT64:
3856 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3857 atomic_type = int64_type_kind;
3860 case SPECIFIER_INT128:
3861 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3862 atomic_type = int128_type_kind;
3865 case SPECIFIER_FLOAT:
3866 atomic_type = ATOMIC_TYPE_FLOAT;
3868 case SPECIFIER_DOUBLE:
3869 atomic_type = ATOMIC_TYPE_DOUBLE;
3871 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3872 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3874 case SPECIFIER_BOOL:
3875 atomic_type = ATOMIC_TYPE_BOOL;
3877 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3878 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3879 atomic_type = ATOMIC_TYPE_FLOAT;
3881 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3882 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3883 atomic_type = ATOMIC_TYPE_DOUBLE;
3885 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3886 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3887 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3890 /* invalid specifier combination, give an error message */
3891 if (type_specifiers == 0) {
3895 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3896 if (!(c_mode & _CXX) && !strict_mode) {
3897 if (warning.implicit_int) {
3898 warningf(HERE, "no type specifiers in declaration, using 'int'");
3900 atomic_type = ATOMIC_TYPE_INT;
3903 errorf(HERE, "no type specifiers given in declaration");
3905 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3906 (type_specifiers & SPECIFIER_UNSIGNED)) {
3907 errorf(HERE, "signed and unsigned specifiers given");
3908 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3909 errorf(HERE, "only integer types can be signed or unsigned");
3911 errorf(HERE, "multiple datatypes in declaration");
3916 if (type_specifiers & SPECIFIER_COMPLEX) {
3917 type = allocate_type_zero(TYPE_COMPLEX);
3918 type->complex.akind = atomic_type;
3919 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3920 type = allocate_type_zero(TYPE_IMAGINARY);
3921 type->imaginary.akind = atomic_type;
3923 type = allocate_type_zero(TYPE_ATOMIC);
3924 type->atomic.akind = atomic_type;
3927 } else if (type_specifiers != 0) {
3928 errorf(HERE, "multiple datatypes in declaration");
3931 /* FIXME: check type qualifiers here */
3933 type->base.qualifiers = qualifiers;
3934 type->base.modifiers = modifiers;
3936 type_t *result = typehash_insert(type);
3937 if (newtype && result != type) {
3941 specifiers->type = result;
3945 specifiers->type = type_error_type;
3949 static type_qualifiers_t parse_type_qualifiers(void)
3951 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3954 switch (token.type) {
3955 /* type qualifiers */
3956 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3957 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3958 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3959 /* microsoft extended type modifiers */
3960 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3961 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3962 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3963 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3964 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3973 * Parses an K&R identifier list
3975 static void parse_identifier_list(scope_t *scope)
3978 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
3979 entity->base.source_position = token.source_position;
3980 entity->base.namespc = NAMESPACE_NORMAL;
3981 entity->base.symbol = token.v.symbol;
3982 /* a K&R parameter has no type, yet */
3985 append_entity(scope, entity);
3987 if (token.type != ',') {
3991 } while (token.type == T_IDENTIFIER);
3994 static type_t *automatic_type_conversion(type_t *orig_type);
3996 static void semantic_parameter(declaration_t *declaration)
3998 /* TODO: improve error messages */
3999 source_position_t const* const pos = &declaration->base.source_position;
4002 switch (declaration->declared_storage_class) {
4003 /* Allowed storage classes */
4004 case STORAGE_CLASS_NONE:
4005 case STORAGE_CLASS_REGISTER:
4009 errorf(pos, "parameter may only have none or register storage class");
4013 type_t *const orig_type = declaration->type;
4014 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
4015 * sugar. Turn it into a pointer.
4016 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
4017 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4019 type_t *const type = automatic_type_conversion(orig_type);
4020 declaration->type = type;
4022 if (is_type_incomplete(skip_typeref(type))) {
4023 errorf(pos, "parameter '%#T' is of incomplete type",
4024 orig_type, declaration->base.symbol);
4028 static entity_t *parse_parameter(void)
4030 declaration_specifiers_t specifiers;
4031 memset(&specifiers, 0, sizeof(specifiers));
4033 parse_declaration_specifiers(&specifiers);
4035 entity_t *entity = parse_declarator(&specifiers, true, false);
4040 * Parses function type parameters (and optionally creates variable_t entities
4041 * for them in a scope)
4043 static void parse_parameters(function_type_t *type, scope_t *scope)
4046 add_anchor_token(')');
4047 int saved_comma_state = save_and_reset_anchor_state(',');
4049 if (token.type == T_IDENTIFIER &&
4050 !is_typedef_symbol(token.v.symbol)) {
4051 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4052 if (la1_type == ',' || la1_type == ')') {
4053 type->kr_style_parameters = true;
4054 parse_identifier_list(scope);
4055 goto parameters_finished;
4059 if (token.type == ')') {
4060 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4061 if (!(c_mode & _CXX))
4062 type->unspecified_parameters = true;
4063 goto parameters_finished;
4066 function_parameter_t *parameter;
4067 function_parameter_t *last_parameter = NULL;
4070 switch (token.type) {
4073 type->variadic = true;
4074 goto parameters_finished;
4077 case T___extension__:
4080 entity_t *entity = parse_parameter();
4081 if (entity->kind == ENTITY_TYPEDEF) {
4082 errorf(&entity->base.source_position,
4083 "typedef not allowed as function parameter");
4086 assert(is_declaration(entity));
4088 /* func(void) is not a parameter */
4089 if (last_parameter == NULL
4090 && token.type == ')'
4091 && entity->base.symbol == NULL
4092 && skip_typeref(entity->declaration.type) == type_void) {
4093 goto parameters_finished;
4095 semantic_parameter(&entity->declaration);
4097 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4098 memset(parameter, 0, sizeof(parameter[0]));
4099 parameter->type = entity->declaration.type;
4101 if (scope != NULL) {
4102 append_entity(scope, entity);
4105 if (last_parameter != NULL) {
4106 last_parameter->next = parameter;
4108 type->parameters = parameter;
4110 last_parameter = parameter;
4115 goto parameters_finished;
4117 if (token.type != ',') {
4118 goto parameters_finished;
4124 parameters_finished:
4125 rem_anchor_token(')');
4129 restore_anchor_state(',', saved_comma_state);
4132 typedef enum construct_type_kind_t {
4137 } construct_type_kind_t;
4139 typedef struct construct_type_t construct_type_t;
4140 struct construct_type_t {
4141 construct_type_kind_t kind;
4142 construct_type_t *next;
4145 typedef struct parsed_pointer_t parsed_pointer_t;
4146 struct parsed_pointer_t {
4147 construct_type_t construct_type;
4148 type_qualifiers_t type_qualifiers;
4151 typedef struct construct_function_type_t construct_function_type_t;
4152 struct construct_function_type_t {
4153 construct_type_t construct_type;
4154 type_t *function_type;
4157 typedef struct parsed_array_t parsed_array_t;
4158 struct parsed_array_t {
4159 construct_type_t construct_type;
4160 type_qualifiers_t type_qualifiers;
4166 typedef struct construct_base_type_t construct_base_type_t;
4167 struct construct_base_type_t {
4168 construct_type_t construct_type;
4172 static construct_type_t *parse_pointer_declarator(void)
4176 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4177 memset(pointer, 0, sizeof(pointer[0]));
4178 pointer->construct_type.kind = CONSTRUCT_POINTER;
4179 pointer->type_qualifiers = parse_type_qualifiers();
4181 return (construct_type_t*) pointer;
4184 static construct_type_t *parse_array_declarator(void)
4187 add_anchor_token(']');
4189 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4190 memset(array, 0, sizeof(array[0]));
4191 array->construct_type.kind = CONSTRUCT_ARRAY;
4193 if (token.type == T_static) {
4194 array->is_static = true;
4198 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4199 if (type_qualifiers != 0) {
4200 if (token.type == T_static) {
4201 array->is_static = true;
4205 array->type_qualifiers = type_qualifiers;
4207 if (token.type == '*' && look_ahead(1)->type == ']') {
4208 array->is_variable = true;
4210 } else if (token.type != ']') {
4211 array->size = parse_assignment_expression();
4214 rem_anchor_token(']');
4218 return (construct_type_t*) array;
4221 static construct_type_t *parse_function_declarator(scope_t *scope)
4223 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4225 /* TODO: revive this... once we know exactly how to do it */
4227 decl_modifiers_t modifiers = entity->declaration.modifiers;
4229 unsigned mask = modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4231 if (mask & (mask-1)) {
4232 const char *first = NULL, *second = NULL;
4234 /* more than one calling convention set */
4235 if (modifiers & DM_CDECL) {
4236 if (first == NULL) first = "cdecl";
4237 else if (second == NULL) second = "cdecl";
4239 if (modifiers & DM_STDCALL) {
4240 if (first == NULL) first = "stdcall";
4241 else if (second == NULL) second = "stdcall";
4243 if (modifiers & DM_FASTCALL) {
4244 if (first == NULL) first = "fastcall";
4245 else if (second == NULL) second = "fastcall";
4247 if (modifiers & DM_THISCALL) {
4248 if (first == NULL) first = "thiscall";
4249 else if (second == NULL) second = "thiscall";
4251 errorf(&entity->base.source_position,
4252 "%s and %s attributes are not compatible", first, second);
4255 if (modifiers & DM_CDECL)
4256 type->function.calling_convention = CC_CDECL;
4257 else if (modifiers & DM_STDCALL)
4258 type->function.calling_convention = CC_STDCALL;
4259 else if (modifiers & DM_FASTCALL)
4260 type->function.calling_convention = CC_FASTCALL;
4261 else if (modifiers & DM_THISCALL)
4262 type->function.calling_convention = CC_THISCALL;
4265 parse_parameters(&type->function, scope);
4267 construct_function_type_t *construct_function_type =
4268 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4269 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4270 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4271 construct_function_type->function_type = type;
4273 return &construct_function_type->construct_type;
4276 typedef struct parse_declarator_env_t {
4277 decl_modifiers_t modifiers;
4279 source_position_t source_position;
4281 } parse_declarator_env_t;
4283 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4284 bool may_be_abstract)
4286 /* construct a single linked list of construct_type_t's which describe
4287 * how to construct the final declarator type */
4288 construct_type_t *first = NULL;
4289 construct_type_t *last = NULL;
4290 gnu_attribute_t *attributes = NULL;
4292 decl_modifiers_t modifiers = parse_attributes(&attributes);
4295 while (token.type == '*') {
4296 construct_type_t *type = parse_pointer_declarator();
4306 /* TODO: find out if this is correct */
4307 modifiers |= parse_attributes(&attributes);
4311 env->modifiers |= modifiers;
4313 construct_type_t *inner_types = NULL;
4315 switch (token.type) {
4318 errorf(HERE, "no identifier expected in typename");
4320 env->symbol = token.v.symbol;
4321 env->source_position = token.source_position;
4327 add_anchor_token(')');
4328 inner_types = parse_inner_declarator(env, may_be_abstract);
4329 if (inner_types != NULL) {
4330 /* All later declarators only modify the return type */
4333 rem_anchor_token(')');
4337 if (may_be_abstract)
4339 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4344 construct_type_t *p = last;
4347 construct_type_t *type;
4348 switch (token.type) {
4350 scope_t *scope = NULL;
4352 scope = &env->parameters;
4354 type = parse_function_declarator(scope);
4358 type = parse_array_declarator();
4361 goto declarator_finished;
4364 /* insert in the middle of the list (behind p) */
4366 type->next = p->next;
4377 declarator_finished:
4378 /* append inner_types at the end of the list, we don't to set last anymore
4379 * as it's not needed anymore */
4381 assert(first == NULL);
4382 first = inner_types;
4384 last->next = inner_types;
4392 static void parse_declaration_attributes(entity_t *entity)
4394 gnu_attribute_t *attributes = NULL;
4395 decl_modifiers_t modifiers = parse_attributes(&attributes);
4401 if (entity->kind == ENTITY_TYPEDEF) {
4402 modifiers |= entity->typedefe.modifiers;
4403 type = entity->typedefe.type;
4405 assert(is_declaration(entity));
4406 modifiers |= entity->declaration.modifiers;
4407 type = entity->declaration.type;
4412 /* handle these strange/stupid mode attributes */
4413 gnu_attribute_t *attribute = attributes;
4414 for ( ; attribute != NULL; attribute = attribute->next) {
4415 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4418 atomic_type_kind_t akind = attribute->u.akind;
4419 if (!is_type_signed(type)) {
4421 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4422 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4423 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4424 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4426 panic("invalid akind in mode attribute");
4430 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4431 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4432 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4433 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4435 panic("invalid akind in mode attribute");
4439 type = make_atomic_type(akind, type->base.qualifiers);
4442 type_modifiers_t type_modifiers = type->base.modifiers;
4443 if (modifiers & DM_TRANSPARENT_UNION)
4444 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4446 if (type->base.modifiers != type_modifiers) {
4447 type_t *copy = duplicate_type(type);
4448 copy->base.modifiers = type_modifiers;
4450 type = typehash_insert(copy);
4452 obstack_free(type_obst, copy);
4456 if (entity->kind == ENTITY_TYPEDEF) {
4457 entity->typedefe.type = type;
4458 entity->typedefe.modifiers = modifiers;
4460 entity->declaration.type = type;
4461 entity->declaration.modifiers = modifiers;
4465 static type_t *construct_declarator_type(construct_type_t *construct_list,
4468 construct_type_t *iter = construct_list;
4469 for( ; iter != NULL; iter = iter->next) {
4470 switch (iter->kind) {
4471 case CONSTRUCT_INVALID:
4472 internal_errorf(HERE, "invalid type construction found");
4473 case CONSTRUCT_FUNCTION: {
4474 construct_function_type_t *construct_function_type
4475 = (construct_function_type_t*) iter;
4477 type_t *function_type = construct_function_type->function_type;
4479 function_type->function.return_type = type;
4481 type_t *skipped_return_type = skip_typeref(type);
4483 if (is_type_function(skipped_return_type)) {
4484 errorf(HERE, "function returning function is not allowed");
4485 } else if (is_type_array(skipped_return_type)) {
4486 errorf(HERE, "function returning array is not allowed");
4488 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4490 "type qualifiers in return type of function type are meaningless");
4494 type = function_type;
4498 case CONSTRUCT_POINTER: {
4499 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4500 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4504 case CONSTRUCT_ARRAY: {
4505 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4506 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4508 expression_t *size_expression = parsed_array->size;
4509 if (size_expression != NULL) {
4511 = create_implicit_cast(size_expression, type_size_t);
4514 array_type->base.qualifiers = parsed_array->type_qualifiers;
4515 array_type->array.element_type = type;
4516 array_type->array.is_static = parsed_array->is_static;
4517 array_type->array.is_variable = parsed_array->is_variable;
4518 array_type->array.size_expression = size_expression;
4520 if (size_expression != NULL) {
4521 if (is_constant_expression(size_expression)) {
4522 array_type->array.size_constant = true;
4523 array_type->array.size
4524 = fold_constant(size_expression);
4526 array_type->array.is_vla = true;
4530 type_t *skipped_type = skip_typeref(type);
4532 if (is_type_incomplete(skipped_type)) {
4533 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4534 } else if (is_type_function(skipped_type)) {
4535 errorf(HERE, "array of functions is not allowed");
4542 type_t *hashed_type = typehash_insert(type);
4543 if (hashed_type != type) {
4544 /* the function type was constructed earlier freeing it here will
4545 * destroy other types... */
4546 if (iter->kind != CONSTRUCT_FUNCTION) {
4556 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4557 bool may_be_abstract,
4558 bool create_compound_member)
4560 parse_declarator_env_t env;
4561 memset(&env, 0, sizeof(env));
4563 construct_type_t *construct_type
4564 = parse_inner_declarator(&env, may_be_abstract);
4565 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4567 if (construct_type != NULL) {
4568 obstack_free(&temp_obst, construct_type);
4572 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4573 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4574 entity->base.symbol = env.symbol;
4575 entity->base.source_position = env.source_position;
4576 entity->typedefe.type = type;
4578 if (create_compound_member) {
4579 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4580 } else if (is_type_function(skip_typeref(type))) {
4581 entity = allocate_entity_zero(ENTITY_FUNCTION);
4583 entity->function.is_inline = specifiers->is_inline;
4584 entity->function.parameters = env.parameters;
4586 entity = allocate_entity_zero(ENTITY_VARIABLE);
4588 entity->variable.get_property_sym = specifiers->get_property_sym;
4589 entity->variable.put_property_sym = specifiers->put_property_sym;
4590 if (specifiers->alignment != 0) {
4591 /* TODO: add checks here */
4592 entity->variable.alignment = specifiers->alignment;
4595 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4596 warningf(&env.source_position,
4597 "variable '%Y' declared 'inline'\n", env.symbol);
4601 entity->base.source_position = env.source_position;
4602 entity->base.symbol = env.symbol;
4603 entity->base.namespc = NAMESPACE_NORMAL;
4604 entity->declaration.type = type;
4605 entity->declaration.modifiers = env.modifiers | specifiers->modifiers;
4606 entity->declaration.deprecated_string = specifiers->deprecated_string;
4608 storage_class_t storage_class = specifiers->storage_class;
4609 entity->declaration.declared_storage_class = storage_class;
4611 if (storage_class == STORAGE_CLASS_NONE && scope != file_scope) {
4612 storage_class = STORAGE_CLASS_AUTO;
4614 entity->declaration.storage_class = storage_class;
4617 parse_declaration_attributes(entity);
4622 static type_t *parse_abstract_declarator(type_t *base_type)
4624 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4626 type_t *result = construct_declarator_type(construct_type, base_type);
4627 if (construct_type != NULL) {
4628 obstack_free(&temp_obst, construct_type);
4635 * Check if the declaration of main is suspicious. main should be a
4636 * function with external linkage, returning int, taking either zero
4637 * arguments, two, or three arguments of appropriate types, ie.
4639 * int main([ int argc, char **argv [, char **env ] ]).
4641 * @param decl the declaration to check
4642 * @param type the function type of the declaration
4644 static void check_type_of_main(const entity_t *entity)
4646 const source_position_t *pos = &entity->base.source_position;
4647 if (entity->kind != ENTITY_FUNCTION) {
4648 warningf(pos, "'main' is not a function");
4652 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4653 warningf(pos, "'main' is normally a non-static function");
4656 type_t *type = skip_typeref(entity->declaration.type);
4657 assert(is_type_function(type));
4659 function_type_t *func_type = &type->function;
4660 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4661 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4662 func_type->return_type);
4664 const function_parameter_t *parm = func_type->parameters;
4666 type_t *const first_type = parm->type;
4667 if (!types_compatible(skip_typeref(first_type), type_int)) {
4669 "first argument of 'main' should be 'int', but is '%T'",
4674 type_t *const second_type = parm->type;
4675 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4676 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4680 type_t *const third_type = parm->type;
4681 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4682 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4686 goto warn_arg_count;
4690 warningf(pos, "'main' takes only zero, two or three arguments");
4696 * Check if a symbol is the equal to "main".
4698 static bool is_sym_main(const symbol_t *const sym)
4700 return strcmp(sym->string, "main") == 0;
4704 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4705 * for various problems that occur for multiple definitions
4707 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4709 const symbol_t *const symbol = entity->base.symbol;
4710 const namespace_t namespc = entity->base.namespc;
4711 const source_position_t *pos = &entity->base.source_position;
4713 assert(symbol != NULL);
4714 entity_t *previous_entity = get_entity(symbol, namespc);
4715 /* pushing the same entity twice will break the stack structure */
4716 assert(previous_entity != entity);
4718 if (entity->kind == ENTITY_FUNCTION) {
4719 type_t *const orig_type = entity->declaration.type;
4720 type_t *const type = skip_typeref(orig_type);
4722 assert(is_type_function(type));
4723 if (type->function.unspecified_parameters &&
4724 warning.strict_prototypes &&
4725 previous_entity == NULL) {
4726 warningf(pos, "function declaration '%#T' is not a prototype",
4730 if (warning.main && scope == file_scope && is_sym_main(symbol)) {
4731 check_type_of_main(entity);
4735 if (is_declaration(entity)) {
4736 if (warning.nested_externs
4737 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4738 && scope != file_scope) {
4739 warningf(pos, "nested extern declaration of '%#T'",
4740 entity->declaration.type, symbol);
4744 if (previous_entity != NULL
4745 && previous_entity->base.parent_scope == ¤t_function->parameters
4746 && scope->depth == previous_entity->base.parent_scope->depth + 1) {
4748 assert(previous_entity->kind == ENTITY_VARIABLE);
4750 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4751 entity->declaration.type, symbol,
4752 previous_entity->declaration.type, symbol,
4753 &previous_entity->base.source_position);
4757 if (previous_entity != NULL
4758 && previous_entity->base.parent_scope == scope) {
4760 if (previous_entity->kind != entity->kind) {
4762 "redeclaration of '%Y' as different kind of symbol (declared %P)",
4763 symbol, &previous_entity->base.source_position);
4766 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4768 "redeclaration of enum entry '%Y' (declared %P)",
4769 symbol, &previous_entity->base.source_position);
4772 if (previous_entity->kind == ENTITY_TYPEDEF) {
4773 /* TODO: C++ allows this for exactly the same type */
4775 "redefinition of typedef '%Y' (declared %P)",
4776 symbol, &previous_entity->base.source_position);
4780 /* at this point we should have only VARIABLES or FUNCTIONS */
4781 assert(is_declaration(previous_entity) && is_declaration(entity));
4783 /* can happen for K&R style declarations */
4784 if (previous_entity->kind == ENTITY_VARIABLE
4785 && previous_entity->declaration.type == NULL
4786 && entity->kind == ENTITY_VARIABLE) {
4787 previous_entity->declaration.type = entity->declaration.type;
4788 previous_entity->declaration.storage_class
4789 = entity->declaration.storage_class;
4790 previous_entity->declaration.declared_storage_class
4791 = entity->declaration.declared_storage_class;
4792 previous_entity->declaration.modifiers
4793 = entity->declaration.modifiers;
4794 previous_entity->declaration.deprecated_string
4795 = entity->declaration.deprecated_string;
4797 assert(entity->declaration.type != NULL);
4799 declaration_t *const previous_declaration
4800 = &previous_entity->declaration;
4801 declaration_t *const declaration = &entity->declaration;
4802 type_t *const orig_type = entity->declaration.type;
4803 type_t *const type = skip_typeref(orig_type);
4805 type_t *prev_type = skip_typeref(previous_declaration->type);
4807 if (!types_compatible(type, prev_type)) {
4809 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4810 orig_type, symbol, previous_declaration->type, symbol,
4811 &previous_entity->base.source_position);
4813 unsigned old_storage_class = previous_declaration->storage_class;
4814 if (warning.redundant_decls && is_definition
4815 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4816 && !(previous_declaration->modifiers & DM_USED)
4817 && !previous_declaration->used) {
4818 warningf(&previous_entity->base.source_position,
4819 "unnecessary static forward declaration for '%#T'",
4820 previous_declaration->type, symbol);
4823 unsigned new_storage_class = declaration->storage_class;
4824 if (is_type_incomplete(prev_type)) {
4825 previous_declaration->type = type;
4829 /* pretend no storage class means extern for function
4830 * declarations (except if the previous declaration is neither
4831 * none nor extern) */
4832 if (entity->kind == ENTITY_FUNCTION) {
4833 if (prev_type->function.unspecified_parameters) {
4834 previous_declaration->type = type;
4838 switch (old_storage_class) {
4839 case STORAGE_CLASS_NONE:
4840 old_storage_class = STORAGE_CLASS_EXTERN;
4843 case STORAGE_CLASS_EXTERN:
4844 if (is_definition) {
4845 if (warning.missing_prototypes &&
4846 prev_type->function.unspecified_parameters &&
4847 !is_sym_main(symbol)) {
4848 warningf(pos, "no previous prototype for '%#T'",
4851 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4852 new_storage_class = STORAGE_CLASS_EXTERN;
4861 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4862 new_storage_class == STORAGE_CLASS_EXTERN) {
4863 warn_redundant_declaration:
4864 if (!is_definition &&
4865 warning.redundant_decls &&
4866 is_type_valid(prev_type) &&
4867 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4869 "redundant declaration for '%Y' (declared %P)",
4870 symbol, &previous_entity->base.source_position);
4872 } else if (current_function == NULL) {
4873 if (old_storage_class != STORAGE_CLASS_STATIC &&
4874 new_storage_class == STORAGE_CLASS_STATIC) {
4876 "static declaration of '%Y' follows non-static declaration (declared %P)",
4877 symbol, &previous_entity->base.source_position);
4878 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4879 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4880 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4882 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4884 goto error_redeclaration;
4885 goto warn_redundant_declaration;
4887 } else if (is_type_valid(prev_type)) {
4888 if (old_storage_class == new_storage_class) {
4889 error_redeclaration:
4890 errorf(pos, "redeclaration of '%Y' (declared %P)",
4891 symbol, &previous_entity->base.source_position);
4894 "redeclaration of '%Y' with different linkage (declared %P)",
4895 symbol, &previous_entity->base.source_position);
4900 previous_declaration->modifiers |= declaration->modifiers;
4901 if (entity->kind == ENTITY_FUNCTION) {
4902 previous_entity->function.is_inline |= entity->function.is_inline;
4904 return previous_entity;
4907 if (entity->kind == ENTITY_FUNCTION) {
4908 if (is_definition &&
4909 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4910 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4911 warningf(pos, "no previous prototype for '%#T'",
4912 entity->declaration.type, symbol);
4913 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4914 warningf(pos, "no previous declaration for '%#T'",
4915 entity->declaration.type, symbol);
4918 } else if (warning.missing_declarations
4919 && entity->kind == ENTITY_VARIABLE
4920 && scope == file_scope) {
4921 declaration_t *declaration = &entity->declaration;
4922 if (declaration->storage_class == STORAGE_CLASS_NONE ||
4923 declaration->storage_class == STORAGE_CLASS_THREAD) {
4924 warningf(pos, "no previous declaration for '%#T'",
4925 declaration->type, symbol);
4930 assert(entity->base.parent_scope == NULL);
4931 assert(scope != NULL);
4933 entity->base.parent_scope = scope;
4934 entity->base.namespc = NAMESPACE_NORMAL;
4935 environment_push(entity);
4936 append_entity(scope, entity);
4941 static void parser_error_multiple_definition(entity_t *entity,
4942 const source_position_t *source_position)
4944 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4945 entity->base.symbol, &entity->base.source_position);
4948 static bool is_declaration_specifier(const token_t *token,
4949 bool only_specifiers_qualifiers)
4951 switch (token->type) {
4956 return is_typedef_symbol(token->v.symbol);
4958 case T___extension__:
4960 return !only_specifiers_qualifiers;
4967 static void parse_init_declarator_rest(entity_t *entity)
4969 assert(is_declaration(entity));
4970 declaration_t *const declaration = &entity->declaration;
4974 type_t *orig_type = declaration->type;
4975 type_t *type = skip_typeref(orig_type);
4977 if (entity->kind == ENTITY_VARIABLE
4978 && entity->variable.initializer != NULL) {
4979 parser_error_multiple_definition(entity, HERE);
4982 bool must_be_constant = false;
4983 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4984 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
4985 entity->base.parent_scope == file_scope) {
4986 must_be_constant = true;
4989 if (is_type_function(type)) {
4990 errorf(&entity->base.source_position,
4991 "function '%#T' is initialized like a variable",
4992 orig_type, entity->base.symbol);
4993 orig_type = type_error_type;
4996 parse_initializer_env_t env;
4997 env.type = orig_type;
4998 env.must_be_constant = must_be_constant;
4999 env.entity = entity;
5000 current_init_decl = entity;
5002 initializer_t *initializer = parse_initializer(&env);
5003 current_init_decl = NULL;
5005 if (entity->kind == ENTITY_VARIABLE) {
5006 /* § 6.7.5 (22) array initializers for arrays with unknown size
5007 * determine the array type size */
5008 declaration->type = env.type;
5009 entity->variable.initializer = initializer;
5013 /* parse rest of a declaration without any declarator */
5014 static void parse_anonymous_declaration_rest(
5015 const declaration_specifiers_t *specifiers)
5019 if (warning.other) {
5020 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5021 warningf(&specifiers->source_position,
5022 "useless storage class in empty declaration");
5025 type_t *type = specifiers->type;
5026 switch (type->kind) {
5027 case TYPE_COMPOUND_STRUCT:
5028 case TYPE_COMPOUND_UNION: {
5029 if (type->compound.compound->base.symbol == NULL) {
5030 warningf(&specifiers->source_position,
5031 "unnamed struct/union that defines no instances");
5040 warningf(&specifiers->source_position, "empty declaration");
5046 static void parse_declaration_rest(entity_t *ndeclaration,
5047 const declaration_specifiers_t *specifiers,
5048 parsed_declaration_func finished_declaration)
5050 add_anchor_token(';');
5051 add_anchor_token(',');
5053 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5055 if (token.type == '=') {
5056 parse_init_declarator_rest(entity);
5059 if (token.type != ',')
5063 add_anchor_token('=');
5064 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5065 rem_anchor_token('=');
5070 rem_anchor_token(';');
5071 rem_anchor_token(',');
5074 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5076 symbol_t *symbol = entity->base.symbol;
5077 if (symbol == NULL) {
5078 errorf(HERE, "anonymous declaration not valid as function parameter");
5082 assert(entity->base.namespc == NAMESPACE_NORMAL);
5083 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5084 if (previous_entity == NULL
5085 || previous_entity->base.parent_scope != scope) {
5086 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5091 if (is_definition) {
5092 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5095 return record_entity(entity, false);
5098 static void parse_declaration(parsed_declaration_func finished_declaration)
5100 declaration_specifiers_t specifiers;
5101 memset(&specifiers, 0, sizeof(specifiers));
5103 add_anchor_token(';');
5104 parse_declaration_specifiers(&specifiers);
5105 rem_anchor_token(';');
5107 if (token.type == ';') {
5108 parse_anonymous_declaration_rest(&specifiers);
5110 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5111 parse_declaration_rest(entity, &specifiers, finished_declaration);
5115 static type_t *get_default_promoted_type(type_t *orig_type)
5117 type_t *result = orig_type;
5119 type_t *type = skip_typeref(orig_type);
5120 if (is_type_integer(type)) {
5121 result = promote_integer(type);
5122 } else if (type == type_float) {
5123 result = type_double;
5129 static void parse_kr_declaration_list(entity_t *entity)
5131 if (entity->kind != ENTITY_FUNCTION)
5134 type_t *type = skip_typeref(entity->declaration.type);
5135 assert(is_type_function(type));
5136 if (!type->function.kr_style_parameters)
5140 add_anchor_token('{');
5142 /* push function parameters */
5143 size_t const top = environment_top();
5144 scope_push(&entity->function.parameters);
5146 entity_t *parameter = entity->function.parameters.entities;
5147 for ( ; parameter != NULL; parameter = parameter->base.next) {
5148 assert(parameter->base.parent_scope == NULL);
5149 parameter->base.parent_scope = scope;
5150 environment_push(parameter);
5153 /* parse declaration list */
5154 while (is_declaration_specifier(&token, false)) {
5155 parse_declaration(finished_kr_declaration);
5158 /* pop function parameters */
5159 assert(scope == &entity->function.parameters);
5161 environment_pop_to(top);
5163 /* update function type */
5164 type_t *new_type = duplicate_type(type);
5166 function_parameter_t *parameters = NULL;
5167 function_parameter_t *last_parameter = NULL;
5169 entity_t *parameter_declaration = entity->function.parameters.entities;
5170 for( ; parameter_declaration != NULL;
5171 parameter_declaration = parameter_declaration->base.next) {
5172 type_t *parameter_type = parameter_declaration->declaration.type;
5173 if (parameter_type == NULL) {
5175 errorf(HERE, "no type specified for function parameter '%Y'",
5176 parameter_declaration->base.symbol);
5178 if (warning.implicit_int) {
5179 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5180 parameter_declaration->base.symbol);
5182 parameter_type = type_int;
5183 parameter_declaration->declaration.type = parameter_type;
5187 semantic_parameter(¶meter_declaration->declaration);
5188 parameter_type = parameter_declaration->declaration.type;
5191 * we need the default promoted types for the function type
5193 parameter_type = get_default_promoted_type(parameter_type);
5195 function_parameter_t *function_parameter
5196 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5197 memset(function_parameter, 0, sizeof(function_parameter[0]));
5199 function_parameter->type = parameter_type;
5200 if (last_parameter != NULL) {
5201 last_parameter->next = function_parameter;
5203 parameters = function_parameter;
5205 last_parameter = function_parameter;
5208 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5210 new_type->function.parameters = parameters;
5211 new_type->function.unspecified_parameters = true;
5213 type = typehash_insert(new_type);
5214 if (type != new_type) {
5215 obstack_free(type_obst, new_type);
5218 entity->declaration.type = type;
5220 rem_anchor_token('{');
5223 static bool first_err = true;
5226 * When called with first_err set, prints the name of the current function,
5229 static void print_in_function(void)
5233 diagnosticf("%s: In function '%Y':\n",
5234 current_function->base.base.source_position.input_name,
5235 current_function->base.base.symbol);
5240 * Check if all labels are defined in the current function.
5241 * Check if all labels are used in the current function.
5243 static void check_labels(void)
5245 for (const goto_statement_t *goto_statement = goto_first;
5246 goto_statement != NULL;
5247 goto_statement = goto_statement->next) {
5248 /* skip computed gotos */
5249 if (goto_statement->expression != NULL)
5252 label_t *label = goto_statement->label;
5255 if (label->base.source_position.input_name == NULL) {
5256 print_in_function();
5257 errorf(&goto_statement->base.source_position,
5258 "label '%Y' used but not defined", label->base.symbol);
5264 if (warning.unused_label) {
5265 for (const label_statement_t *label_statement = label_first;
5266 label_statement != NULL;
5267 label_statement = label_statement->next) {
5268 label_t *label = label_statement->label;
5270 if (! label->used) {
5271 print_in_function();
5272 warningf(&label_statement->base.source_position,
5273 "label '%Y' defined but not used", label->base.symbol);
5277 label_first = label_last = NULL;
5280 static void warn_unused_decl(entity_t *entity, entity_t *end,
5281 char const *const what)
5283 for (; entity != NULL; entity = entity->base.next) {
5284 if (!is_declaration(entity))
5287 declaration_t *declaration = &entity->declaration;
5288 if (declaration->implicit)
5291 if (!declaration->used) {
5292 print_in_function();
5293 warningf(&entity->base.source_position, "%s '%Y' is unused",
5294 what, entity->base.symbol);
5295 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5296 print_in_function();
5297 warningf(&entity->base.source_position, "%s '%Y' is never read",
5298 what, entity->base.symbol);
5306 static void check_unused_variables(statement_t *const stmt, void *const env)
5310 switch (stmt->kind) {
5311 case STATEMENT_DECLARATION: {
5312 declaration_statement_t const *const decls = &stmt->declaration;
5313 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5319 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5328 * Check declarations of current_function for unused entities.
5330 static void check_declarations(void)
5332 if (warning.unused_parameter) {
5333 const scope_t *scope = ¤t_function->parameters;
5335 /* do not issue unused warnings for main */
5336 if (!is_sym_main(current_function->base.base.symbol)) {
5337 warn_unused_decl(scope->entities, NULL, "parameter");
5340 if (warning.unused_variable) {
5341 walk_statements(current_function->statement, check_unused_variables,
5346 static int determine_truth(expression_t const* const cond)
5349 !is_constant_expression(cond) ? 0 :
5350 fold_constant(cond) != 0 ? 1 :
5354 static bool expression_returns(expression_t const *const expr)
5356 switch (expr->kind) {
5358 expression_t const *const func = expr->call.function;
5359 if (func->kind == EXPR_REFERENCE) {
5360 entity_t *entity = func->reference.entity;
5361 if (entity->kind == ENTITY_FUNCTION
5362 && entity->declaration.modifiers & DM_NORETURN)
5366 if (!expression_returns(func))
5369 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5370 if (!expression_returns(arg->expression))
5377 case EXPR_REFERENCE:
5378 case EXPR_REFERENCE_ENUM_VALUE:
5380 case EXPR_CHARACTER_CONSTANT:
5381 case EXPR_WIDE_CHARACTER_CONSTANT:
5382 case EXPR_STRING_LITERAL:
5383 case EXPR_WIDE_STRING_LITERAL:
5384 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5385 case EXPR_LABEL_ADDRESS:
5386 case EXPR_CLASSIFY_TYPE:
5387 case EXPR_SIZEOF: // TODO handle obscure VLA case
5390 case EXPR_BUILTIN_SYMBOL:
5391 case EXPR_BUILTIN_CONSTANT_P:
5392 case EXPR_BUILTIN_PREFETCH:
5395 case EXPR_STATEMENT: // TODO implement
5398 case EXPR_CONDITIONAL:
5399 // TODO handle constant expression
5401 expression_returns(expr->conditional.condition) && (
5402 expression_returns(expr->conditional.true_expression) ||
5403 expression_returns(expr->conditional.false_expression)
5407 return expression_returns(expr->select.compound);
5409 case EXPR_ARRAY_ACCESS:
5411 expression_returns(expr->array_access.array_ref) &&
5412 expression_returns(expr->array_access.index);
5415 return expression_returns(expr->va_starte.ap);
5418 return expression_returns(expr->va_arge.ap);
5420 EXPR_UNARY_CASES_MANDATORY
5421 return expression_returns(expr->unary.value);
5423 case EXPR_UNARY_THROW:
5427 // TODO handle constant lhs of && and ||
5429 expression_returns(expr->binary.left) &&
5430 expression_returns(expr->binary.right);
5436 panic("unhandled expression");
5439 static bool noreturn_candidate;
5441 static void check_reachable(statement_t *const stmt)
5443 if (stmt->base.reachable)
5445 if (stmt->kind != STATEMENT_DO_WHILE)
5446 stmt->base.reachable = true;
5448 statement_t *last = stmt;
5450 switch (stmt->kind) {
5451 case STATEMENT_INVALID:
5452 case STATEMENT_EMPTY:
5453 case STATEMENT_DECLARATION:
5454 case STATEMENT_LOCAL_LABEL:
5456 next = stmt->base.next;
5459 case STATEMENT_COMPOUND:
5460 next = stmt->compound.statements;
5463 case STATEMENT_RETURN:
5464 noreturn_candidate = false;
5467 case STATEMENT_IF: {
5468 if_statement_t const* const ifs = &stmt->ifs;
5469 int const val = determine_truth(ifs->condition);
5472 check_reachable(ifs->true_statement);
5477 if (ifs->false_statement != NULL) {
5478 check_reachable(ifs->false_statement);
5482 next = stmt->base.next;
5486 case STATEMENT_SWITCH: {
5487 switch_statement_t const *const switchs = &stmt->switchs;
5488 expression_t const *const expr = switchs->expression;
5490 if (is_constant_expression(expr)) {
5491 long const val = fold_constant(expr);
5492 case_label_statement_t * defaults = NULL;
5493 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5494 if (i->expression == NULL) {
5499 if (i->first_case <= val && val <= i->last_case) {
5500 check_reachable((statement_t*)i);
5505 if (defaults != NULL) {
5506 check_reachable((statement_t*)defaults);
5510 bool has_default = false;
5511 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5512 if (i->expression == NULL)
5515 check_reachable((statement_t*)i);
5522 next = stmt->base.next;
5526 case STATEMENT_EXPRESSION: {
5527 /* Check for noreturn function call */
5528 expression_t const *const expr = stmt->expression.expression;
5529 if (!expression_returns(expr))
5532 next = stmt->base.next;
5536 case STATEMENT_CONTINUE: {
5537 statement_t *parent = stmt;
5539 parent = parent->base.parent;
5540 if (parent == NULL) /* continue not within loop */
5544 switch (parent->kind) {
5545 case STATEMENT_WHILE: goto continue_while;
5546 case STATEMENT_DO_WHILE: goto continue_do_while;
5547 case STATEMENT_FOR: goto continue_for;
5554 case STATEMENT_BREAK: {
5555 statement_t *parent = stmt;
5557 parent = parent->base.parent;
5558 if (parent == NULL) /* break not within loop/switch */
5561 switch (parent->kind) {
5562 case STATEMENT_SWITCH:
5563 case STATEMENT_WHILE:
5564 case STATEMENT_DO_WHILE:
5567 next = parent->base.next;
5568 goto found_break_parent;
5577 case STATEMENT_GOTO:
5578 if (stmt->gotos.expression) {
5579 statement_t *parent = stmt->base.parent;
5580 if (parent == NULL) /* top level goto */
5584 next = stmt->gotos.label->statement;
5585 if (next == NULL) /* missing label */
5590 case STATEMENT_LABEL:
5591 next = stmt->label.statement;
5594 case STATEMENT_CASE_LABEL:
5595 next = stmt->case_label.statement;
5598 case STATEMENT_WHILE: {
5599 while_statement_t const *const whiles = &stmt->whiles;
5600 int const val = determine_truth(whiles->condition);
5603 check_reachable(whiles->body);
5608 next = stmt->base.next;
5612 case STATEMENT_DO_WHILE:
5613 next = stmt->do_while.body;
5616 case STATEMENT_FOR: {
5617 for_statement_t *const fors = &stmt->fors;
5619 if (fors->condition_reachable)
5621 fors->condition_reachable = true;
5623 expression_t const *const cond = fors->condition;
5625 cond == NULL ? 1 : determine_truth(cond);
5628 check_reachable(fors->body);
5633 next = stmt->base.next;
5637 case STATEMENT_MS_TRY: {
5638 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5639 check_reachable(ms_try->try_statement);
5640 next = ms_try->final_statement;
5644 case STATEMENT_LEAVE: {
5645 statement_t *parent = stmt;
5647 parent = parent->base.parent;
5648 if (parent == NULL) /* __leave not within __try */
5651 if (parent->kind == STATEMENT_MS_TRY) {
5653 next = parent->ms_try.final_statement;
5661 while (next == NULL) {
5662 next = last->base.parent;
5664 noreturn_candidate = false;
5666 type_t *const type = current_function->base.type;
5667 assert(is_type_function(type));
5668 type_t *const ret = skip_typeref(type->function.return_type);
5669 if (warning.return_type &&
5670 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5671 is_type_valid(ret) &&
5672 !is_sym_main(current_function->base.base.symbol)) {
5673 warningf(&stmt->base.source_position,
5674 "control reaches end of non-void function");
5679 switch (next->kind) {
5680 case STATEMENT_INVALID:
5681 case STATEMENT_EMPTY:
5682 case STATEMENT_DECLARATION:
5683 case STATEMENT_LOCAL_LABEL:
5684 case STATEMENT_EXPRESSION:
5686 case STATEMENT_RETURN:
5687 case STATEMENT_CONTINUE:
5688 case STATEMENT_BREAK:
5689 case STATEMENT_GOTO:
5690 case STATEMENT_LEAVE:
5691 panic("invalid control flow in function");
5693 case STATEMENT_COMPOUND:
5695 case STATEMENT_SWITCH:
5696 case STATEMENT_LABEL:
5697 case STATEMENT_CASE_LABEL:
5699 next = next->base.next;
5702 case STATEMENT_WHILE: {
5704 if (next->base.reachable)
5706 next->base.reachable = true;
5708 while_statement_t const *const whiles = &next->whiles;
5709 int const val = determine_truth(whiles->condition);
5712 check_reachable(whiles->body);
5718 next = next->base.next;
5722 case STATEMENT_DO_WHILE: {
5724 if (next->base.reachable)
5726 next->base.reachable = true;
5728 do_while_statement_t const *const dw = &next->do_while;
5729 int const val = determine_truth(dw->condition);
5732 check_reachable(dw->body);
5738 next = next->base.next;
5742 case STATEMENT_FOR: {
5744 for_statement_t *const fors = &next->fors;
5746 fors->step_reachable = true;
5748 if (fors->condition_reachable)
5750 fors->condition_reachable = true;
5752 expression_t const *const cond = fors->condition;
5754 cond == NULL ? 1 : determine_truth(cond);
5757 check_reachable(fors->body);
5763 next = next->base.next;
5767 case STATEMENT_MS_TRY:
5769 next = next->ms_try.final_statement;
5774 check_reachable(next);
5777 static void check_unreachable(statement_t* const stmt, void *const env)
5781 switch (stmt->kind) {
5782 case STATEMENT_DO_WHILE:
5783 if (!stmt->base.reachable) {
5784 expression_t const *const cond = stmt->do_while.condition;
5785 if (determine_truth(cond) >= 0) {
5786 warningf(&cond->base.source_position,
5787 "condition of do-while-loop is unreachable");
5792 case STATEMENT_FOR: {
5793 for_statement_t const* const fors = &stmt->fors;
5795 // if init and step are unreachable, cond is unreachable, too
5796 if (!stmt->base.reachable && !fors->step_reachable) {
5797 warningf(&stmt->base.source_position, "statement is unreachable");
5799 if (!stmt->base.reachable && fors->initialisation != NULL) {
5800 warningf(&fors->initialisation->base.source_position,
5801 "initialisation of for-statement is unreachable");
5804 if (!fors->condition_reachable && fors->condition != NULL) {
5805 warningf(&fors->condition->base.source_position,
5806 "condition of for-statement is unreachable");
5809 if (!fors->step_reachable && fors->step != NULL) {
5810 warningf(&fors->step->base.source_position,
5811 "step of for-statement is unreachable");
5817 case STATEMENT_COMPOUND:
5818 if (stmt->compound.statements != NULL)
5823 if (!stmt->base.reachable)
5824 warningf(&stmt->base.source_position, "statement is unreachable");
5829 static void parse_external_declaration(void)
5831 /* function-definitions and declarations both start with declaration
5833 declaration_specifiers_t specifiers;
5834 memset(&specifiers, 0, sizeof(specifiers));
5836 add_anchor_token(';');
5837 parse_declaration_specifiers(&specifiers);
5838 rem_anchor_token(';');
5840 /* must be a declaration */
5841 if (token.type == ';') {
5842 parse_anonymous_declaration_rest(&specifiers);
5846 add_anchor_token(',');
5847 add_anchor_token('=');
5848 add_anchor_token(';');
5849 add_anchor_token('{');
5851 /* declarator is common to both function-definitions and declarations */
5852 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5854 rem_anchor_token('{');
5855 rem_anchor_token(';');
5856 rem_anchor_token('=');
5857 rem_anchor_token(',');
5859 /* must be a declaration */
5860 switch (token.type) {
5864 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
5868 /* must be a function definition */
5869 parse_kr_declaration_list(ndeclaration);
5871 if (token.type != '{') {
5872 parse_error_expected("while parsing function definition", '{', NULL);
5873 eat_until_matching_token(';');
5877 assert(is_declaration(ndeclaration));
5878 type_t *type = ndeclaration->declaration.type;
5880 /* note that we don't skip typerefs: the standard doesn't allow them here
5881 * (so we can't use is_type_function here) */
5882 if (type->kind != TYPE_FUNCTION) {
5883 if (is_type_valid(type)) {
5884 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5885 type, ndeclaration->base.symbol);
5891 if (warning.aggregate_return &&
5892 is_type_compound(skip_typeref(type->function.return_type))) {
5893 warningf(HERE, "function '%Y' returns an aggregate",
5894 ndeclaration->base.symbol);
5896 if (warning.traditional && !type->function.unspecified_parameters) {
5897 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5898 ndeclaration->base.symbol);
5900 if (warning.old_style_definition && type->function.unspecified_parameters) {
5901 warningf(HERE, "old-style function definition '%Y'",
5902 ndeclaration->base.symbol);
5905 /* § 6.7.5.3 (14) a function definition with () means no
5906 * parameters (and not unspecified parameters) */
5907 if (type->function.unspecified_parameters
5908 && type->function.parameters == NULL
5909 && !type->function.kr_style_parameters) {
5910 type_t *duplicate = duplicate_type(type);
5911 duplicate->function.unspecified_parameters = false;
5913 type = typehash_insert(duplicate);
5914 if (type != duplicate) {
5915 obstack_free(type_obst, duplicate);
5917 ndeclaration->declaration.type = type;
5920 entity_t *const entity = record_entity(ndeclaration, true);
5921 assert(entity->kind == ENTITY_FUNCTION);
5922 assert(ndeclaration->kind == ENTITY_FUNCTION);
5924 function_t *function = &entity->function;
5925 if (ndeclaration != entity) {
5926 function->parameters = ndeclaration->function.parameters;
5928 assert(is_declaration(entity));
5929 type = skip_typeref(entity->declaration.type);
5931 /* push function parameters and switch scope */
5932 size_t const top = environment_top();
5933 scope_push(&function->parameters);
5935 entity_t *parameter = function->parameters.entities;
5936 for( ; parameter != NULL; parameter = parameter->base.next) {
5937 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5938 parameter->base.parent_scope = scope;
5940 assert(parameter->base.parent_scope == NULL
5941 || parameter->base.parent_scope == scope);
5942 parameter->base.parent_scope = scope;
5943 if (parameter->base.symbol == NULL) {
5944 errorf(¶meter->base.source_position, "parameter name omitted");
5947 environment_push(parameter);
5950 if (function->statement != NULL) {
5951 parser_error_multiple_definition(entity, HERE);
5954 /* parse function body */
5955 int label_stack_top = label_top();
5956 function_t *old_current_function = current_function;
5957 current_function = function;
5958 current_parent = NULL;
5960 statement_t *const body = parse_compound_statement(false);
5961 function->statement = body;
5964 check_declarations();
5965 if (warning.return_type ||
5966 warning.unreachable_code ||
5967 (warning.missing_noreturn
5968 && !(function->base.modifiers & DM_NORETURN))) {
5969 noreturn_candidate = true;
5970 check_reachable(body);
5971 if (warning.unreachable_code)
5972 walk_statements(body, check_unreachable, NULL);
5973 if (warning.missing_noreturn &&
5974 noreturn_candidate &&
5975 !(function->base.modifiers & DM_NORETURN)) {
5976 warningf(&body->base.source_position,
5977 "function '%#T' is candidate for attribute 'noreturn'",
5978 type, entity->base.symbol);
5982 assert(current_parent == NULL);
5983 assert(current_function == function);
5984 current_function = old_current_function;
5985 label_pop_to(label_stack_top);
5988 assert(scope == &function->parameters);
5990 environment_pop_to(top);
5993 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5994 source_position_t *source_position,
5995 const symbol_t *symbol)
5997 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5999 type->bitfield.base_type = base_type;
6000 type->bitfield.size_expression = size;
6003 type_t *skipped_type = skip_typeref(base_type);
6004 if (!is_type_integer(skipped_type)) {
6005 errorf(HERE, "bitfield base type '%T' is not an integer type",
6009 bit_size = skipped_type->base.size * 8;
6012 if (is_constant_expression(size)) {
6013 long v = fold_constant(size);
6016 errorf(source_position, "negative width in bit-field '%Y'",
6018 } else if (v == 0) {
6019 errorf(source_position, "zero width for bit-field '%Y'",
6021 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6022 errorf(source_position, "width of '%Y' exceeds its type",
6025 type->bitfield.bit_size = v;
6032 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6034 entity_t *iter = compound->members.entities;
6035 for( ; iter != NULL; iter = iter->base.next) {
6036 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6039 if (iter->base.symbol == NULL) {
6040 type_t *type = skip_typeref(iter->declaration.type);
6041 if (is_type_compound(type)) {
6043 = find_compound_entry(type->compound.compound, symbol);
6050 if (iter->base.symbol == symbol) {
6058 static void parse_compound_declarators(compound_t *compound,
6059 const declaration_specifiers_t *specifiers)
6064 if (token.type == ':') {
6065 source_position_t source_position = *HERE;
6068 type_t *base_type = specifiers->type;
6069 expression_t *size = parse_constant_expression();
6071 type_t *type = make_bitfield_type(base_type, size,
6072 &source_position, sym_anonymous);
6074 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6075 entity->base.namespc = NAMESPACE_NORMAL;
6076 entity->base.source_position = source_position;
6077 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6078 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6079 entity->declaration.modifiers = specifiers->modifiers;
6080 entity->declaration.type = type;
6082 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6083 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6085 if (token.type == ':') {
6086 source_position_t source_position = *HERE;
6088 expression_t *size = parse_constant_expression();
6090 type_t *type = entity->declaration.type;
6091 type_t *bitfield_type = make_bitfield_type(type, size,
6092 &source_position, entity->base.symbol);
6093 entity->declaration.type = bitfield_type;
6097 /* make sure we don't define a symbol multiple times */
6098 symbol_t *symbol = entity->base.symbol;
6099 if (symbol != NULL) {
6100 entity_t *prev = find_compound_entry(compound, symbol);
6103 assert(prev->base.symbol == symbol);
6104 errorf(&entity->base.source_position,
6105 "multiple declarations of symbol '%Y' (declared %P)",
6106 symbol, &prev->base.source_position);
6110 append_entity(&compound->members, entity);
6112 if (token.type != ',')
6122 static void semantic_compound(compound_t *compound)
6124 entity_t *entity = compound->members.entities;
6125 for ( ; entity != NULL; entity = entity->base.next) {
6126 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6128 type_t *orig_type = entity->declaration.type;
6129 type_t *type = skip_typeref(orig_type);
6131 if (is_type_function(type)) {
6133 "compound member '%Y' must not have function type '%T'",
6134 entity->base.symbol, orig_type);
6135 } else if (is_type_incomplete(type)) {
6136 /* §6.7.2.1 (16) flexible array member */
6137 if (is_type_array(type) && entity->base.next == NULL) {
6138 compound->has_flexible_member = true;
6141 "compound member '%Y' has incomplete type '%T'",
6142 entity->base.symbol, orig_type);
6148 static void parse_compound_type_entries(compound_t *compound)
6151 add_anchor_token('}');
6153 while (token.type != '}') {
6154 if (token.type == T_EOF) {
6155 errorf(HERE, "EOF while parsing struct");
6158 declaration_specifiers_t specifiers;
6159 memset(&specifiers, 0, sizeof(specifiers));
6160 parse_declaration_specifiers(&specifiers);
6162 parse_compound_declarators(compound, &specifiers);
6164 semantic_compound(compound);
6165 rem_anchor_token('}');
6169 static type_t *parse_typename(void)
6171 declaration_specifiers_t specifiers;
6172 memset(&specifiers, 0, sizeof(specifiers));
6173 parse_declaration_specifiers(&specifiers);
6174 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6175 /* TODO: improve error message, user does probably not know what a
6176 * storage class is...
6178 errorf(HERE, "typename may not have a storage class");
6181 type_t *result = parse_abstract_declarator(specifiers.type);
6189 typedef expression_t* (*parse_expression_function)(void);
6190 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6192 typedef struct expression_parser_function_t expression_parser_function_t;
6193 struct expression_parser_function_t {
6194 parse_expression_function parser;
6195 unsigned infix_precedence;
6196 parse_expression_infix_function infix_parser;
6199 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6202 * Prints an error message if an expression was expected but not read
6204 static expression_t *expected_expression_error(void)
6206 /* skip the error message if the error token was read */
6207 if (token.type != T_ERROR) {
6208 errorf(HERE, "expected expression, got token '%K'", &token);
6212 return create_invalid_expression();
6216 * Parse a string constant.
6218 static expression_t *parse_string_const(void)
6221 if (token.type == T_STRING_LITERAL) {
6222 string_t res = token.v.string;
6224 while (token.type == T_STRING_LITERAL) {
6225 res = concat_strings(&res, &token.v.string);
6228 if (token.type != T_WIDE_STRING_LITERAL) {
6229 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6230 /* note: that we use type_char_ptr here, which is already the
6231 * automatic converted type. revert_automatic_type_conversion
6232 * will construct the array type */
6233 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6234 cnst->string.value = res;
6238 wres = concat_string_wide_string(&res, &token.v.wide_string);
6240 wres = token.v.wide_string;
6245 switch (token.type) {
6246 case T_WIDE_STRING_LITERAL:
6247 wres = concat_wide_strings(&wres, &token.v.wide_string);
6250 case T_STRING_LITERAL:
6251 wres = concat_wide_string_string(&wres, &token.v.string);
6255 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6256 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6257 cnst->wide_string.value = wres;
6266 * Parse a boolean constant.
6268 static expression_t *parse_bool_const(bool value)
6270 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6271 cnst->base.type = type_bool;
6272 cnst->conste.v.int_value = value;
6280 * Parse an integer constant.
6282 static expression_t *parse_int_const(void)
6284 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6285 cnst->base.type = token.datatype;
6286 cnst->conste.v.int_value = token.v.intvalue;
6294 * Parse a character constant.
6296 static expression_t *parse_character_constant(void)
6298 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6299 cnst->base.type = token.datatype;
6300 cnst->conste.v.character = token.v.string;
6302 if (cnst->conste.v.character.size != 1) {
6303 if (warning.multichar && GNU_MODE) {
6304 warningf(HERE, "multi-character character constant");
6306 errorf(HERE, "more than 1 characters in character constant");
6315 * Parse a wide character constant.
6317 static expression_t *parse_wide_character_constant(void)
6319 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6320 cnst->base.type = token.datatype;
6321 cnst->conste.v.wide_character = token.v.wide_string;
6323 if (cnst->conste.v.wide_character.size != 1) {
6324 if (warning.multichar && GNU_MODE) {
6325 warningf(HERE, "multi-character character constant");
6327 errorf(HERE, "more than 1 characters in character constant");
6336 * Parse a float constant.
6338 static expression_t *parse_float_const(void)
6340 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6341 cnst->base.type = token.datatype;
6342 cnst->conste.v.float_value = token.v.floatvalue;
6349 static entity_t *create_implicit_function(symbol_t *symbol,
6350 const source_position_t *source_position)
6352 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6353 ntype->function.return_type = type_int;
6354 ntype->function.unspecified_parameters = true;
6356 type_t *type = typehash_insert(ntype);
6357 if (type != ntype) {
6361 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6362 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6363 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6364 entity->declaration.type = type;
6365 entity->declaration.implicit = true;
6366 entity->base.symbol = symbol;
6367 entity->base.source_position = *source_position;
6369 bool strict_prototypes_old = warning.strict_prototypes;
6370 warning.strict_prototypes = false;
6371 record_entity(entity, false);
6372 warning.strict_prototypes = strict_prototypes_old;
6378 * Creates a return_type (func)(argument_type) function type if not
6381 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6382 type_t *argument_type2)
6384 function_parameter_t *parameter2
6385 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6386 memset(parameter2, 0, sizeof(parameter2[0]));
6387 parameter2->type = argument_type2;
6389 function_parameter_t *parameter1
6390 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6391 memset(parameter1, 0, sizeof(parameter1[0]));
6392 parameter1->type = argument_type1;
6393 parameter1->next = parameter2;
6395 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6396 type->function.return_type = return_type;
6397 type->function.parameters = parameter1;
6399 type_t *result = typehash_insert(type);
6400 if (result != type) {
6408 * Creates a return_type (func)(argument_type) function type if not
6411 * @param return_type the return type
6412 * @param argument_type the argument type
6414 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6416 function_parameter_t *parameter
6417 = obstack_alloc(type_obst, sizeof(parameter[0]));
6418 memset(parameter, 0, sizeof(parameter[0]));
6419 parameter->type = argument_type;
6421 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6422 type->function.return_type = return_type;
6423 type->function.parameters = parameter;
6425 type_t *result = typehash_insert(type);
6426 if (result != type) {
6433 static type_t *make_function_0_type(type_t *return_type)
6435 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6436 type->function.return_type = return_type;
6437 type->function.parameters = NULL;
6439 type_t *result = typehash_insert(type);
6440 if (result != type) {
6448 * Creates a function type for some function like builtins.
6450 * @param symbol the symbol describing the builtin
6452 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6454 switch (symbol->ID) {
6455 case T___builtin_alloca:
6456 return make_function_1_type(type_void_ptr, type_size_t);
6457 case T___builtin_huge_val:
6458 return make_function_0_type(type_double);
6459 case T___builtin_inf:
6460 return make_function_0_type(type_double);
6461 case T___builtin_inff:
6462 return make_function_0_type(type_float);
6463 case T___builtin_infl:
6464 return make_function_0_type(type_long_double);
6465 case T___builtin_nan:
6466 return make_function_1_type(type_double, type_char_ptr);
6467 case T___builtin_nanf:
6468 return make_function_1_type(type_float, type_char_ptr);
6469 case T___builtin_nanl:
6470 return make_function_1_type(type_long_double, type_char_ptr);
6471 case T___builtin_va_end:
6472 return make_function_1_type(type_void, type_valist);
6473 case T___builtin_expect:
6474 return make_function_2_type(type_long, type_long, type_long);
6476 internal_errorf(HERE, "not implemented builtin symbol found");
6481 * Performs automatic type cast as described in § 6.3.2.1.
6483 * @param orig_type the original type
6485 static type_t *automatic_type_conversion(type_t *orig_type)
6487 type_t *type = skip_typeref(orig_type);
6488 if (is_type_array(type)) {
6489 array_type_t *array_type = &type->array;
6490 type_t *element_type = array_type->element_type;
6491 unsigned qualifiers = array_type->base.qualifiers;
6493 return make_pointer_type(element_type, qualifiers);
6496 if (is_type_function(type)) {
6497 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6504 * reverts the automatic casts of array to pointer types and function
6505 * to function-pointer types as defined § 6.3.2.1
6507 type_t *revert_automatic_type_conversion(const expression_t *expression)
6509 switch (expression->kind) {
6510 case EXPR_REFERENCE: {
6511 entity_t *entity = expression->reference.entity;
6512 if (is_declaration(entity)) {
6513 return entity->declaration.type;
6514 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6515 return entity->enum_value.enum_type;
6517 panic("no declaration or enum in reference");
6522 entity_t *entity = expression->select.compound_entry;
6523 assert(is_declaration(entity));
6524 type_t *type = entity->declaration.type;
6525 return get_qualified_type(type,
6526 expression->base.type->base.qualifiers);
6529 case EXPR_UNARY_DEREFERENCE: {
6530 const expression_t *const value = expression->unary.value;
6531 type_t *const type = skip_typeref(value->base.type);
6532 assert(is_type_pointer(type));
6533 return type->pointer.points_to;
6536 case EXPR_BUILTIN_SYMBOL:
6537 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6539 case EXPR_ARRAY_ACCESS: {
6540 const expression_t *array_ref = expression->array_access.array_ref;
6541 type_t *type_left = skip_typeref(array_ref->base.type);
6542 if (!is_type_valid(type_left))
6544 assert(is_type_pointer(type_left));
6545 return type_left->pointer.points_to;
6548 case EXPR_STRING_LITERAL: {
6549 size_t size = expression->string.value.size;
6550 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6553 case EXPR_WIDE_STRING_LITERAL: {
6554 size_t size = expression->wide_string.value.size;
6555 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6558 case EXPR_COMPOUND_LITERAL:
6559 return expression->compound_literal.type;
6564 return expression->base.type;
6567 static expression_t *parse_reference(void)
6569 symbol_t *const symbol = token.v.symbol;
6571 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6573 if (entity == NULL) {
6574 if (!strict_mode && look_ahead(1)->type == '(') {
6575 /* an implicitly declared function */
6576 if (warning.implicit_function_declaration) {
6577 warningf(HERE, "implicit declaration of function '%Y'",
6581 entity = create_implicit_function(symbol, HERE);
6583 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6584 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6590 if (is_declaration(entity)) {
6591 orig_type = entity->declaration.type;
6592 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6593 orig_type = entity->enum_value.enum_type;
6594 } else if (entity->kind == ENTITY_TYPEDEF) {
6595 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6598 return create_invalid_expression();
6600 panic("expected declaration or enum value in reference");
6603 /* we always do the auto-type conversions; the & and sizeof parser contains
6604 * code to revert this! */
6605 type_t *type = automatic_type_conversion(orig_type);
6607 expression_kind_t kind = EXPR_REFERENCE;
6608 if (entity->kind == ENTITY_ENUM_VALUE)
6609 kind = EXPR_REFERENCE_ENUM_VALUE;
6611 expression_t *expression = allocate_expression_zero(kind);
6612 expression->reference.entity = entity;
6613 expression->base.type = type;
6615 /* this declaration is used */
6616 if (is_declaration(entity)) {
6617 entity->declaration.used = true;
6620 if (entity->base.parent_scope != file_scope
6621 && entity->base.parent_scope->depth < current_function->parameters.depth
6622 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6623 if (entity->kind == ENTITY_VARIABLE) {
6624 /* access of a variable from an outer function */
6625 entity->variable.address_taken = true;
6627 current_function->need_closure = true;
6630 /* check for deprecated functions */
6631 if (warning.deprecated_declarations
6632 && is_declaration(entity)
6633 && entity->declaration.modifiers & DM_DEPRECATED) {
6634 declaration_t *declaration = &entity->declaration;
6636 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6637 "function" : "variable";
6639 if (declaration->deprecated_string != NULL) {
6640 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6641 prefix, entity->base.symbol, &entity->base.source_position,
6642 declaration->deprecated_string);
6644 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6645 entity->base.symbol, &entity->base.source_position);
6649 if (warning.init_self && entity == current_init_decl && !in_type_prop
6650 && entity->kind == ENTITY_VARIABLE) {
6651 current_init_decl = NULL;
6652 warningf(HERE, "variable '%#T' is initialized by itself",
6653 entity->declaration.type, entity->base.symbol);
6660 static bool semantic_cast(expression_t *cast)
6662 expression_t *expression = cast->unary.value;
6663 type_t *orig_dest_type = cast->base.type;
6664 type_t *orig_type_right = expression->base.type;
6665 type_t const *dst_type = skip_typeref(orig_dest_type);
6666 type_t const *src_type = skip_typeref(orig_type_right);
6667 source_position_t const *pos = &cast->base.source_position;
6669 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6670 if (dst_type == type_void)
6673 /* only integer and pointer can be casted to pointer */
6674 if (is_type_pointer(dst_type) &&
6675 !is_type_pointer(src_type) &&
6676 !is_type_integer(src_type) &&
6677 is_type_valid(src_type)) {
6678 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6682 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6683 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6687 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6688 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6692 if (warning.cast_qual &&
6693 is_type_pointer(src_type) &&
6694 is_type_pointer(dst_type)) {
6695 type_t *src = skip_typeref(src_type->pointer.points_to);
6696 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6697 unsigned missing_qualifiers =
6698 src->base.qualifiers & ~dst->base.qualifiers;
6699 if (missing_qualifiers != 0) {
6701 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6702 missing_qualifiers, orig_type_right);
6708 static expression_t *parse_compound_literal(type_t *type)
6710 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6712 parse_initializer_env_t env;
6715 env.must_be_constant = false;
6716 initializer_t *initializer = parse_initializer(&env);
6719 expression->compound_literal.initializer = initializer;
6720 expression->compound_literal.type = type;
6721 expression->base.type = automatic_type_conversion(type);
6727 * Parse a cast expression.
6729 static expression_t *parse_cast(void)
6731 add_anchor_token(')');
6733 source_position_t source_position = token.source_position;
6735 type_t *type = parse_typename();
6737 rem_anchor_token(')');
6740 if (token.type == '{') {
6741 return parse_compound_literal(type);
6744 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6745 cast->base.source_position = source_position;
6747 expression_t *value = parse_sub_expression(PREC_CAST);
6748 cast->base.type = type;
6749 cast->unary.value = value;
6751 if (! semantic_cast(cast)) {
6752 /* TODO: record the error in the AST. else it is impossible to detect it */
6757 return create_invalid_expression();
6761 * Parse a statement expression.
6763 static expression_t *parse_statement_expression(void)
6765 add_anchor_token(')');
6767 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6769 statement_t *statement = parse_compound_statement(true);
6770 expression->statement.statement = statement;
6772 /* find last statement and use its type */
6773 type_t *type = type_void;
6774 const statement_t *stmt = statement->compound.statements;
6776 while (stmt->base.next != NULL)
6777 stmt = stmt->base.next;
6779 if (stmt->kind == STATEMENT_EXPRESSION) {
6780 type = stmt->expression.expression->base.type;
6782 } else if (warning.other) {
6783 warningf(&expression->base.source_position, "empty statement expression ({})");
6785 expression->base.type = type;
6787 rem_anchor_token(')');
6795 * Parse a parenthesized expression.
6797 static expression_t *parse_parenthesized_expression(void)
6801 switch (token.type) {
6803 /* gcc extension: a statement expression */
6804 return parse_statement_expression();
6808 return parse_cast();
6810 if (is_typedef_symbol(token.v.symbol)) {
6811 return parse_cast();
6815 add_anchor_token(')');
6816 expression_t *result = parse_expression();
6817 rem_anchor_token(')');
6824 static expression_t *parse_function_keyword(void)
6828 if (current_function == NULL) {
6829 errorf(HERE, "'__func__' used outside of a function");
6832 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6833 expression->base.type = type_char_ptr;
6834 expression->funcname.kind = FUNCNAME_FUNCTION;
6841 static expression_t *parse_pretty_function_keyword(void)
6843 if (current_function == NULL) {
6844 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6847 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6848 expression->base.type = type_char_ptr;
6849 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6851 eat(T___PRETTY_FUNCTION__);
6856 static expression_t *parse_funcsig_keyword(void)
6858 if (current_function == NULL) {
6859 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6862 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6863 expression->base.type = type_char_ptr;
6864 expression->funcname.kind = FUNCNAME_FUNCSIG;
6871 static expression_t *parse_funcdname_keyword(void)
6873 if (current_function == NULL) {
6874 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6877 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6878 expression->base.type = type_char_ptr;
6879 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6881 eat(T___FUNCDNAME__);
6886 static designator_t *parse_designator(void)
6888 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6889 result->source_position = *HERE;
6891 if (token.type != T_IDENTIFIER) {
6892 parse_error_expected("while parsing member designator",
6893 T_IDENTIFIER, NULL);
6896 result->symbol = token.v.symbol;
6899 designator_t *last_designator = result;
6901 if (token.type == '.') {
6903 if (token.type != T_IDENTIFIER) {
6904 parse_error_expected("while parsing member designator",
6905 T_IDENTIFIER, NULL);
6908 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6909 designator->source_position = *HERE;
6910 designator->symbol = token.v.symbol;
6913 last_designator->next = designator;
6914 last_designator = designator;
6917 if (token.type == '[') {
6919 add_anchor_token(']');
6920 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6921 designator->source_position = *HERE;
6922 designator->array_index = parse_expression();
6923 rem_anchor_token(']');
6925 if (designator->array_index == NULL) {
6929 last_designator->next = designator;
6930 last_designator = designator;
6942 * Parse the __builtin_offsetof() expression.
6944 static expression_t *parse_offsetof(void)
6946 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6947 expression->base.type = type_size_t;
6949 eat(T___builtin_offsetof);
6952 add_anchor_token(',');
6953 type_t *type = parse_typename();
6954 rem_anchor_token(',');
6956 add_anchor_token(')');
6957 designator_t *designator = parse_designator();
6958 rem_anchor_token(')');
6961 expression->offsetofe.type = type;
6962 expression->offsetofe.designator = designator;
6965 memset(&path, 0, sizeof(path));
6966 path.top_type = type;
6967 path.path = NEW_ARR_F(type_path_entry_t, 0);
6969 descend_into_subtype(&path);
6971 if (!walk_designator(&path, designator, true)) {
6972 return create_invalid_expression();
6975 DEL_ARR_F(path.path);
6979 return create_invalid_expression();
6983 * Parses a _builtin_va_start() expression.
6985 static expression_t *parse_va_start(void)
6987 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6989 eat(T___builtin_va_start);
6992 add_anchor_token(',');
6993 expression->va_starte.ap = parse_assignment_expression();
6994 rem_anchor_token(',');
6996 expression_t *const expr = parse_assignment_expression();
6997 if (expr->kind == EXPR_REFERENCE) {
6998 entity_t *const entity = expr->reference.entity;
6999 if (entity->base.parent_scope != ¤t_function->parameters
7000 || entity->base.next != NULL
7001 || entity->kind != ENTITY_VARIABLE) {
7002 errorf(&expr->base.source_position,
7003 "second argument of 'va_start' must be last parameter of the current function");
7005 expression->va_starte.parameter = &entity->variable;
7012 return create_invalid_expression();
7016 * Parses a _builtin_va_arg() expression.
7018 static expression_t *parse_va_arg(void)
7020 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7022 eat(T___builtin_va_arg);
7025 expression->va_arge.ap = parse_assignment_expression();
7027 expression->base.type = parse_typename();
7032 return create_invalid_expression();
7035 static expression_t *parse_builtin_symbol(void)
7037 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7039 symbol_t *symbol = token.v.symbol;
7041 expression->builtin_symbol.symbol = symbol;
7044 type_t *type = get_builtin_symbol_type(symbol);
7045 type = automatic_type_conversion(type);
7047 expression->base.type = type;
7052 * Parses a __builtin_constant() expression.
7054 static expression_t *parse_builtin_constant(void)
7056 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7058 eat(T___builtin_constant_p);
7061 add_anchor_token(')');
7062 expression->builtin_constant.value = parse_assignment_expression();
7063 rem_anchor_token(')');
7065 expression->base.type = type_int;
7069 return create_invalid_expression();
7073 * Parses a __builtin_prefetch() expression.
7075 static expression_t *parse_builtin_prefetch(void)
7077 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7079 eat(T___builtin_prefetch);
7082 add_anchor_token(')');
7083 expression->builtin_prefetch.adr = parse_assignment_expression();
7084 if (token.type == ',') {
7086 expression->builtin_prefetch.rw = parse_assignment_expression();
7088 if (token.type == ',') {
7090 expression->builtin_prefetch.locality = parse_assignment_expression();
7092 rem_anchor_token(')');
7094 expression->base.type = type_void;
7098 return create_invalid_expression();
7102 * Parses a __builtin_is_*() compare expression.
7104 static expression_t *parse_compare_builtin(void)
7106 expression_t *expression;
7108 switch (token.type) {
7109 case T___builtin_isgreater:
7110 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7112 case T___builtin_isgreaterequal:
7113 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7115 case T___builtin_isless:
7116 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7118 case T___builtin_islessequal:
7119 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7121 case T___builtin_islessgreater:
7122 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7124 case T___builtin_isunordered:
7125 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7128 internal_errorf(HERE, "invalid compare builtin found");
7130 expression->base.source_position = *HERE;
7134 expression->binary.left = parse_assignment_expression();
7136 expression->binary.right = parse_assignment_expression();
7139 type_t *const orig_type_left = expression->binary.left->base.type;
7140 type_t *const orig_type_right = expression->binary.right->base.type;
7142 type_t *const type_left = skip_typeref(orig_type_left);
7143 type_t *const type_right = skip_typeref(orig_type_right);
7144 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7145 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7146 type_error_incompatible("invalid operands in comparison",
7147 &expression->base.source_position, orig_type_left, orig_type_right);
7150 semantic_comparison(&expression->binary);
7155 return create_invalid_expression();
7160 * Parses a __builtin_expect() expression.
7162 static expression_t *parse_builtin_expect(void)
7164 expression_t *expression
7165 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7167 eat(T___builtin_expect);
7170 expression->binary.left = parse_assignment_expression();
7172 expression->binary.right = parse_constant_expression();
7175 expression->base.type = expression->binary.left->base.type;
7179 return create_invalid_expression();
7184 * Parses a MS assume() expression.
7186 static expression_t *parse_assume(void)
7188 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7193 add_anchor_token(')');
7194 expression->unary.value = parse_assignment_expression();
7195 rem_anchor_token(')');
7198 expression->base.type = type_void;
7201 return create_invalid_expression();
7205 * Return the declaration for a given label symbol or create a new one.
7207 * @param symbol the symbol of the label
7209 static label_t *get_label(symbol_t *symbol)
7212 assert(current_function != NULL);
7214 label = get_entity(symbol, NAMESPACE_LABEL);
7215 /* if we found a local label, we already created the declaration */
7216 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7217 if (label->base.parent_scope != scope) {
7218 assert(label->base.parent_scope->depth < scope->depth);
7219 current_function->goto_to_outer = true;
7221 return &label->label;
7224 label = get_entity(symbol, NAMESPACE_LABEL);
7225 /* if we found a label in the same function, then we already created the
7228 && label->base.parent_scope == ¤t_function->parameters) {
7229 return &label->label;
7232 /* otherwise we need to create a new one */
7233 label = allocate_entity_zero(ENTITY_LABEL);
7234 label->base.namespc = NAMESPACE_LABEL;
7235 label->base.symbol = symbol;
7239 return &label->label;
7243 * Parses a GNU && label address expression.
7245 static expression_t *parse_label_address(void)
7247 source_position_t source_position = token.source_position;
7249 if (token.type != T_IDENTIFIER) {
7250 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7253 symbol_t *symbol = token.v.symbol;
7256 label_t *label = get_label(symbol);
7258 label->address_taken = true;
7260 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7261 expression->base.source_position = source_position;
7263 /* label address is threaten as a void pointer */
7264 expression->base.type = type_void_ptr;
7265 expression->label_address.label = label;
7268 return create_invalid_expression();
7272 * Parse a microsoft __noop expression.
7274 static expression_t *parse_noop_expression(void)
7276 /* the result is a (int)0 */
7277 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7278 cnst->base.type = type_int;
7279 cnst->conste.v.int_value = 0;
7280 cnst->conste.is_ms_noop = true;
7284 if (token.type == '(') {
7285 /* parse arguments */
7287 add_anchor_token(')');
7288 add_anchor_token(',');
7290 if (token.type != ')') {
7292 (void)parse_assignment_expression();
7293 if (token.type != ',')
7299 rem_anchor_token(',');
7300 rem_anchor_token(')');
7308 * Parses a primary expression.
7310 static expression_t *parse_primary_expression(void)
7312 switch (token.type) {
7313 case T_false: return parse_bool_const(false);
7314 case T_true: return parse_bool_const(true);
7315 case T_INTEGER: return parse_int_const();
7316 case T_CHARACTER_CONSTANT: return parse_character_constant();
7317 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7318 case T_FLOATINGPOINT: return parse_float_const();
7319 case T_STRING_LITERAL:
7320 case T_WIDE_STRING_LITERAL: return parse_string_const();
7321 case T_IDENTIFIER: return parse_reference();
7322 case T___FUNCTION__:
7323 case T___func__: return parse_function_keyword();
7324 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7325 case T___FUNCSIG__: return parse_funcsig_keyword();
7326 case T___FUNCDNAME__: return parse_funcdname_keyword();
7327 case T___builtin_offsetof: return parse_offsetof();
7328 case T___builtin_va_start: return parse_va_start();
7329 case T___builtin_va_arg: return parse_va_arg();
7330 case T___builtin_expect:
7331 case T___builtin_alloca:
7332 case T___builtin_inf:
7333 case T___builtin_inff:
7334 case T___builtin_infl:
7335 case T___builtin_nan:
7336 case T___builtin_nanf:
7337 case T___builtin_nanl:
7338 case T___builtin_huge_val:
7339 case T___builtin_va_end: return parse_builtin_symbol();
7340 case T___builtin_isgreater:
7341 case T___builtin_isgreaterequal:
7342 case T___builtin_isless:
7343 case T___builtin_islessequal:
7344 case T___builtin_islessgreater:
7345 case T___builtin_isunordered: return parse_compare_builtin();
7346 case T___builtin_constant_p: return parse_builtin_constant();
7347 case T___builtin_prefetch: return parse_builtin_prefetch();
7348 case T__assume: return parse_assume();
7351 return parse_label_address();
7354 case '(': return parse_parenthesized_expression();
7355 case T___noop: return parse_noop_expression();
7358 errorf(HERE, "unexpected token %K, expected an expression", &token);
7359 return create_invalid_expression();
7363 * Check if the expression has the character type and issue a warning then.
7365 static void check_for_char_index_type(const expression_t *expression)
7367 type_t *const type = expression->base.type;
7368 const type_t *const base_type = skip_typeref(type);
7370 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7371 warning.char_subscripts) {
7372 warningf(&expression->base.source_position,
7373 "array subscript has type '%T'", type);
7377 static expression_t *parse_array_expression(expression_t *left)
7379 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7382 add_anchor_token(']');
7384 expression_t *inside = parse_expression();
7386 type_t *const orig_type_left = left->base.type;
7387 type_t *const orig_type_inside = inside->base.type;
7389 type_t *const type_left = skip_typeref(orig_type_left);
7390 type_t *const type_inside = skip_typeref(orig_type_inside);
7392 type_t *return_type;
7393 array_access_expression_t *array_access = &expression->array_access;
7394 if (is_type_pointer(type_left)) {
7395 return_type = type_left->pointer.points_to;
7396 array_access->array_ref = left;
7397 array_access->index = inside;
7398 check_for_char_index_type(inside);
7399 } else if (is_type_pointer(type_inside)) {
7400 return_type = type_inside->pointer.points_to;
7401 array_access->array_ref = inside;
7402 array_access->index = left;
7403 array_access->flipped = true;
7404 check_for_char_index_type(left);
7406 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7408 "array access on object with non-pointer types '%T', '%T'",
7409 orig_type_left, orig_type_inside);
7411 return_type = type_error_type;
7412 array_access->array_ref = left;
7413 array_access->index = inside;
7416 expression->base.type = automatic_type_conversion(return_type);
7418 rem_anchor_token(']');
7424 static expression_t *parse_typeprop(expression_kind_t const kind)
7426 expression_t *tp_expression = allocate_expression_zero(kind);
7427 tp_expression->base.type = type_size_t;
7429 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7431 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7433 /* we only refer to a type property, mark this case */
7434 bool old = in_type_prop;
7435 in_type_prop = true;
7438 expression_t *expression;
7439 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7441 add_anchor_token(')');
7442 orig_type = parse_typename();
7443 rem_anchor_token(')');
7446 if (token.type == '{') {
7447 /* It was not sizeof(type) after all. It is sizeof of an expression
7448 * starting with a compound literal */
7449 expression = parse_compound_literal(orig_type);
7450 goto typeprop_expression;
7453 expression = parse_sub_expression(PREC_UNARY);
7455 typeprop_expression:
7456 tp_expression->typeprop.tp_expression = expression;
7458 orig_type = revert_automatic_type_conversion(expression);
7459 expression->base.type = orig_type;
7462 tp_expression->typeprop.type = orig_type;
7463 type_t const* const type = skip_typeref(orig_type);
7464 char const* const wrong_type =
7465 is_type_incomplete(type) ? "incomplete" :
7466 type->kind == TYPE_FUNCTION ? "function designator" :
7467 type->kind == TYPE_BITFIELD ? "bitfield" :
7469 if (wrong_type != NULL) {
7470 errorf(&tp_expression->base.source_position,
7471 "operand of %s expression must not be of %s type '%T'",
7472 what, wrong_type, orig_type);
7477 return tp_expression;
7480 static expression_t *parse_sizeof(void)
7482 return parse_typeprop(EXPR_SIZEOF);
7485 static expression_t *parse_alignof(void)
7487 return parse_typeprop(EXPR_ALIGNOF);
7490 static expression_t *parse_select_expression(expression_t *compound)
7492 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7493 select->select.compound = compound;
7495 assert(token.type == '.' || token.type == T_MINUSGREATER);
7496 bool is_pointer = (token.type == T_MINUSGREATER);
7499 if (token.type != T_IDENTIFIER) {
7500 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7503 symbol_t *symbol = token.v.symbol;
7506 type_t *const orig_type = compound->base.type;
7507 type_t *const type = skip_typeref(orig_type);
7510 bool saw_error = false;
7511 if (is_type_pointer(type)) {
7514 "request for member '%Y' in something not a struct or union, but '%T'",
7518 type_left = skip_typeref(type->pointer.points_to);
7520 if (is_pointer && is_type_valid(type)) {
7521 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7528 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7529 type_left->kind == TYPE_COMPOUND_UNION) {
7530 compound_t *compound = type_left->compound.compound;
7532 if (!compound->complete) {
7533 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7535 goto create_error_entry;
7538 entry = find_compound_entry(compound, symbol);
7539 if (entry == NULL) {
7540 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7541 goto create_error_entry;
7544 if (is_type_valid(type_left) && !saw_error) {
7546 "request for member '%Y' in something not a struct or union, but '%T'",
7550 return create_invalid_expression();
7553 assert(is_declaration(entry));
7554 select->select.compound_entry = entry;
7556 type_t *entry_type = entry->declaration.type;
7558 = get_qualified_type(entry_type, type_left->base.qualifiers);
7560 /* we always do the auto-type conversions; the & and sizeof parser contains
7561 * code to revert this! */
7562 select->base.type = automatic_type_conversion(res_type);
7564 type_t *skipped = skip_typeref(res_type);
7565 if (skipped->kind == TYPE_BITFIELD) {
7566 select->base.type = skipped->bitfield.base_type;
7572 static void check_call_argument(const function_parameter_t *parameter,
7573 call_argument_t *argument, unsigned pos)
7575 type_t *expected_type = parameter->type;
7576 type_t *expected_type_skip = skip_typeref(expected_type);
7577 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7578 expression_t *arg_expr = argument->expression;
7579 type_t *arg_type = skip_typeref(arg_expr->base.type);
7581 /* handle transparent union gnu extension */
7582 if (is_type_union(expected_type_skip)
7583 && (expected_type_skip->base.modifiers
7584 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7585 compound_t *union_decl = expected_type_skip->compound.compound;
7586 type_t *best_type = NULL;
7587 entity_t *entry = union_decl->members.entities;
7588 for ( ; entry != NULL; entry = entry->base.next) {
7589 assert(is_declaration(entry));
7590 type_t *decl_type = entry->declaration.type;
7591 error = semantic_assign(decl_type, arg_expr);
7592 if (error == ASSIGN_ERROR_INCOMPATIBLE
7593 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7596 if (error == ASSIGN_SUCCESS) {
7597 best_type = decl_type;
7598 } else if (best_type == NULL) {
7599 best_type = decl_type;
7603 if (best_type != NULL) {
7604 expected_type = best_type;
7608 error = semantic_assign(expected_type, arg_expr);
7609 argument->expression = create_implicit_cast(argument->expression,
7612 if (error != ASSIGN_SUCCESS) {
7613 /* report exact scope in error messages (like "in argument 3") */
7615 snprintf(buf, sizeof(buf), "call argument %u", pos);
7616 report_assign_error(error, expected_type, arg_expr, buf,
7617 &arg_expr->base.source_position);
7618 } else if (warning.traditional || warning.conversion) {
7619 type_t *const promoted_type = get_default_promoted_type(arg_type);
7620 if (!types_compatible(expected_type_skip, promoted_type) &&
7621 !types_compatible(expected_type_skip, type_void_ptr) &&
7622 !types_compatible(type_void_ptr, promoted_type)) {
7623 /* Deliberately show the skipped types in this warning */
7624 warningf(&arg_expr->base.source_position,
7625 "passing call argument %u as '%T' rather than '%T' due to prototype",
7626 pos, expected_type_skip, promoted_type);
7632 * Parse a call expression, ie. expression '( ... )'.
7634 * @param expression the function address
7636 static expression_t *parse_call_expression(expression_t *expression)
7638 expression_t *result = allocate_expression_zero(EXPR_CALL);
7639 call_expression_t *call = &result->call;
7640 call->function = expression;
7642 type_t *const orig_type = expression->base.type;
7643 type_t *const type = skip_typeref(orig_type);
7645 function_type_t *function_type = NULL;
7646 if (is_type_pointer(type)) {
7647 type_t *const to_type = skip_typeref(type->pointer.points_to);
7649 if (is_type_function(to_type)) {
7650 function_type = &to_type->function;
7651 call->base.type = function_type->return_type;
7655 if (function_type == NULL && is_type_valid(type)) {
7656 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7659 /* parse arguments */
7661 add_anchor_token(')');
7662 add_anchor_token(',');
7664 if (token.type != ')') {
7665 call_argument_t *last_argument = NULL;
7668 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7670 argument->expression = parse_assignment_expression();
7671 if (last_argument == NULL) {
7672 call->arguments = argument;
7674 last_argument->next = argument;
7676 last_argument = argument;
7678 if (token.type != ',')
7683 rem_anchor_token(',');
7684 rem_anchor_token(')');
7687 if (function_type == NULL)
7690 function_parameter_t *parameter = function_type->parameters;
7691 call_argument_t *argument = call->arguments;
7692 if (!function_type->unspecified_parameters) {
7693 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7694 parameter = parameter->next, argument = argument->next) {
7695 check_call_argument(parameter, argument, ++pos);
7698 if (parameter != NULL) {
7699 errorf(HERE, "too few arguments to function '%E'", expression);
7700 } else if (argument != NULL && !function_type->variadic) {
7701 errorf(HERE, "too many arguments to function '%E'", expression);
7705 /* do default promotion */
7706 for( ; argument != NULL; argument = argument->next) {
7707 type_t *type = argument->expression->base.type;
7709 type = get_default_promoted_type(type);
7711 argument->expression
7712 = create_implicit_cast(argument->expression, type);
7715 check_format(&result->call);
7717 if (warning.aggregate_return &&
7718 is_type_compound(skip_typeref(function_type->return_type))) {
7719 warningf(&result->base.source_position,
7720 "function call has aggregate value");
7727 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7729 static bool same_compound_type(const type_t *type1, const type_t *type2)
7732 is_type_compound(type1) &&
7733 type1->kind == type2->kind &&
7734 type1->compound.compound == type2->compound.compound;
7738 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7740 * @param expression the conditional expression
7742 static expression_t *parse_conditional_expression(expression_t *expression)
7744 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7746 conditional_expression_t *conditional = &result->conditional;
7747 conditional->condition = expression;
7750 add_anchor_token(':');
7753 type_t *const condition_type_orig = expression->base.type;
7754 type_t *const condition_type = skip_typeref(condition_type_orig);
7755 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7756 type_error("expected a scalar type in conditional condition",
7757 &expression->base.source_position, condition_type_orig);
7760 expression_t *true_expression = expression;
7761 bool gnu_cond = false;
7762 if (GNU_MODE && token.type == ':') {
7765 true_expression = parse_expression();
7767 rem_anchor_token(':');
7769 expression_t *false_expression =
7770 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7772 type_t *const orig_true_type = true_expression->base.type;
7773 type_t *const orig_false_type = false_expression->base.type;
7774 type_t *const true_type = skip_typeref(orig_true_type);
7775 type_t *const false_type = skip_typeref(orig_false_type);
7778 type_t *result_type;
7779 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7780 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7781 /* ISO/IEC 14882:1998(E) §5.16:2 */
7782 if (true_expression->kind == EXPR_UNARY_THROW) {
7783 result_type = false_type;
7784 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7785 result_type = true_type;
7787 if (warning.other && (
7788 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7789 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7791 warningf(&conditional->base.source_position,
7792 "ISO C forbids conditional expression with only one void side");
7794 result_type = type_void;
7796 } else if (is_type_arithmetic(true_type)
7797 && is_type_arithmetic(false_type)) {
7798 result_type = semantic_arithmetic(true_type, false_type);
7800 true_expression = create_implicit_cast(true_expression, result_type);
7801 false_expression = create_implicit_cast(false_expression, result_type);
7803 conditional->true_expression = true_expression;
7804 conditional->false_expression = false_expression;
7805 conditional->base.type = result_type;
7806 } else if (same_compound_type(true_type, false_type)) {
7807 /* just take 1 of the 2 types */
7808 result_type = true_type;
7809 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7810 type_t *pointer_type;
7812 expression_t *other_expression;
7813 if (is_type_pointer(true_type) &&
7814 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7815 pointer_type = true_type;
7816 other_type = false_type;
7817 other_expression = false_expression;
7819 pointer_type = false_type;
7820 other_type = true_type;
7821 other_expression = true_expression;
7824 if (is_null_pointer_constant(other_expression)) {
7825 result_type = pointer_type;
7826 } else if (is_type_pointer(other_type)) {
7827 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7828 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7831 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7832 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7834 } else if (types_compatible(get_unqualified_type(to1),
7835 get_unqualified_type(to2))) {
7838 if (warning.other) {
7839 warningf(&conditional->base.source_position,
7840 "pointer types '%T' and '%T' in conditional expression are incompatible",
7841 true_type, false_type);
7846 type_t *const type =
7847 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7848 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7849 } else if (is_type_integer(other_type)) {
7850 if (warning.other) {
7851 warningf(&conditional->base.source_position,
7852 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7854 result_type = pointer_type;
7856 if (is_type_valid(other_type)) {
7857 type_error_incompatible("while parsing conditional",
7858 &expression->base.source_position, true_type, false_type);
7860 result_type = type_error_type;
7863 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7864 type_error_incompatible("while parsing conditional",
7865 &conditional->base.source_position, true_type,
7868 result_type = type_error_type;
7871 conditional->true_expression
7872 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7873 conditional->false_expression
7874 = create_implicit_cast(false_expression, result_type);
7875 conditional->base.type = result_type;
7878 return create_invalid_expression();
7882 * Parse an extension expression.
7884 static expression_t *parse_extension(void)
7886 eat(T___extension__);
7888 bool old_gcc_extension = in_gcc_extension;
7889 in_gcc_extension = true;
7890 expression_t *expression = parse_sub_expression(PREC_UNARY);
7891 in_gcc_extension = old_gcc_extension;
7896 * Parse a __builtin_classify_type() expression.
7898 static expression_t *parse_builtin_classify_type(void)
7900 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7901 result->base.type = type_int;
7903 eat(T___builtin_classify_type);
7906 add_anchor_token(')');
7907 expression_t *expression = parse_expression();
7908 rem_anchor_token(')');
7910 result->classify_type.type_expression = expression;
7914 return create_invalid_expression();
7918 * Parse a delete expression
7919 * ISO/IEC 14882:1998(E) §5.3.5
7921 static expression_t *parse_delete(void)
7923 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7924 result->base.type = type_void;
7928 if (token.type == '[') {
7930 result->kind = EXPR_UNARY_DELETE_ARRAY;
7935 expression_t *const value = parse_sub_expression(PREC_CAST);
7936 result->unary.value = value;
7938 type_t *const type = skip_typeref(value->base.type);
7939 if (!is_type_pointer(type)) {
7940 errorf(&value->base.source_position,
7941 "operand of delete must have pointer type");
7942 } else if (warning.other &&
7943 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7944 warningf(&value->base.source_position,
7945 "deleting 'void*' is undefined");
7952 * Parse a throw expression
7953 * ISO/IEC 14882:1998(E) §15:1
7955 static expression_t *parse_throw(void)
7957 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7958 result->base.type = type_void;
7962 expression_t *value = NULL;
7963 switch (token.type) {
7965 value = parse_assignment_expression();
7966 /* ISO/IEC 14882:1998(E) §15.1:3 */
7967 type_t *const orig_type = value->base.type;
7968 type_t *const type = skip_typeref(orig_type);
7969 if (is_type_incomplete(type)) {
7970 errorf(&value->base.source_position,
7971 "cannot throw object of incomplete type '%T'", orig_type);
7972 } else if (is_type_pointer(type)) {
7973 type_t *const points_to = skip_typeref(type->pointer.points_to);
7974 if (is_type_incomplete(points_to) &&
7975 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7976 errorf(&value->base.source_position,
7977 "cannot throw pointer to incomplete type '%T'", orig_type);
7985 result->unary.value = value;
7990 static bool check_pointer_arithmetic(const source_position_t *source_position,
7991 type_t *pointer_type,
7992 type_t *orig_pointer_type)
7994 type_t *points_to = pointer_type->pointer.points_to;
7995 points_to = skip_typeref(points_to);
7997 if (is_type_incomplete(points_to)) {
7998 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7999 errorf(source_position,
8000 "arithmetic with pointer to incomplete type '%T' not allowed",
8003 } else if (warning.pointer_arith) {
8004 warningf(source_position,
8005 "pointer of type '%T' used in arithmetic",
8008 } else if (is_type_function(points_to)) {
8010 errorf(source_position,
8011 "arithmetic with pointer to function type '%T' not allowed",
8014 } else if (warning.pointer_arith) {
8015 warningf(source_position,
8016 "pointer to a function '%T' used in arithmetic",
8023 static bool is_lvalue(const expression_t *expression)
8025 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8026 switch (expression->kind) {
8027 case EXPR_REFERENCE:
8028 case EXPR_ARRAY_ACCESS:
8030 case EXPR_UNARY_DEREFERENCE:
8034 /* Claim it is an lvalue, if the type is invalid. There was a parse
8035 * error before, which maybe prevented properly recognizing it as
8037 return !is_type_valid(skip_typeref(expression->base.type));
8041 static void semantic_incdec(unary_expression_t *expression)
8043 type_t *const orig_type = expression->value->base.type;
8044 type_t *const type = skip_typeref(orig_type);
8045 if (is_type_pointer(type)) {
8046 if (!check_pointer_arithmetic(&expression->base.source_position,
8050 } else if (!is_type_real(type) && is_type_valid(type)) {
8051 /* TODO: improve error message */
8052 errorf(&expression->base.source_position,
8053 "operation needs an arithmetic or pointer type");
8056 if (!is_lvalue(expression->value)) {
8057 /* TODO: improve error message */
8058 errorf(&expression->base.source_position, "lvalue required as operand");
8060 expression->base.type = orig_type;
8063 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8065 type_t *const orig_type = expression->value->base.type;
8066 type_t *const type = skip_typeref(orig_type);
8067 if (!is_type_arithmetic(type)) {
8068 if (is_type_valid(type)) {
8069 /* TODO: improve error message */
8070 errorf(&expression->base.source_position,
8071 "operation needs an arithmetic type");
8076 expression->base.type = orig_type;
8079 static void semantic_unexpr_plus(unary_expression_t *expression)
8081 semantic_unexpr_arithmetic(expression);
8082 if (warning.traditional)
8083 warningf(&expression->base.source_position,
8084 "traditional C rejects the unary plus operator");
8087 static expression_t const *get_reference_address(expression_t const *expr)
8089 bool regular_take_address = true;
8091 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8092 expr = expr->unary.value;
8094 regular_take_address = false;
8097 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8100 expr = expr->unary.value;
8103 /* special case for functions which are automatically converted to a
8104 * pointer to function without an extra TAKE_ADDRESS operation */
8105 if (!regular_take_address && expr->kind == EXPR_REFERENCE
8106 && expr->reference.entity->kind == ENTITY_FUNCTION) {
8113 static void warn_function_address_as_bool(expression_t const* expr)
8115 if (!warning.address)
8118 expr = get_reference_address(expr);
8120 warningf(&expr->base.source_position,
8121 "the address of '%Y' will always evaluate as 'true'",
8122 expr->reference.entity->base.symbol);
8126 static void semantic_not(unary_expression_t *expression)
8128 type_t *const orig_type = expression->value->base.type;
8129 type_t *const type = skip_typeref(orig_type);
8130 if (!is_type_scalar(type) && is_type_valid(type)) {
8131 errorf(&expression->base.source_position,
8132 "operand of ! must be of scalar type");
8135 warn_function_address_as_bool(expression->value);
8137 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8140 static void semantic_unexpr_integer(unary_expression_t *expression)
8142 type_t *const orig_type = expression->value->base.type;
8143 type_t *const type = skip_typeref(orig_type);
8144 if (!is_type_integer(type)) {
8145 if (is_type_valid(type)) {
8146 errorf(&expression->base.source_position,
8147 "operand of ~ must be of integer type");
8152 expression->base.type = orig_type;
8155 static void semantic_dereference(unary_expression_t *expression)
8157 type_t *const orig_type = expression->value->base.type;
8158 type_t *const type = skip_typeref(orig_type);
8159 if (!is_type_pointer(type)) {
8160 if (is_type_valid(type)) {
8161 errorf(&expression->base.source_position,
8162 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8167 type_t *result_type = type->pointer.points_to;
8168 result_type = automatic_type_conversion(result_type);
8169 expression->base.type = result_type;
8173 * Record that an address is taken (expression represents an lvalue).
8175 * @param expression the expression
8176 * @param may_be_register if true, the expression might be an register
8178 static void set_address_taken(expression_t *expression, bool may_be_register)
8180 if (expression->kind != EXPR_REFERENCE)
8183 entity_t *const entity = expression->reference.entity;
8185 if (entity->kind != ENTITY_VARIABLE)
8188 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8189 && !may_be_register) {
8190 errorf(&expression->base.source_position,
8191 "address of register variable '%Y' requested",
8192 entity->base.symbol);
8195 entity->variable.address_taken = true;
8199 * Check the semantic of the address taken expression.
8201 static void semantic_take_addr(unary_expression_t *expression)
8203 expression_t *value = expression->value;
8204 value->base.type = revert_automatic_type_conversion(value);
8206 type_t *orig_type = value->base.type;
8207 type_t *type = skip_typeref(orig_type);
8208 if (!is_type_valid(type))
8212 if (value->kind != EXPR_ARRAY_ACCESS
8213 && value->kind != EXPR_UNARY_DEREFERENCE
8214 && !is_lvalue(value)) {
8215 errorf(&expression->base.source_position,
8216 "'&' requires an lvalue");
8218 if (type->kind == TYPE_BITFIELD) {
8219 errorf(&expression->base.source_position,
8220 "'&' not allowed on object with bitfield type '%T'",
8224 set_address_taken(value, false);
8226 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8229 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8230 static expression_t *parse_##unexpression_type(void) \
8232 expression_t *unary_expression \
8233 = allocate_expression_zero(unexpression_type); \
8235 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8237 sfunc(&unary_expression->unary); \
8239 return unary_expression; \
8242 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8243 semantic_unexpr_arithmetic)
8244 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8245 semantic_unexpr_plus)
8246 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8248 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8249 semantic_dereference)
8250 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8252 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8253 semantic_unexpr_integer)
8254 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8256 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8259 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8261 static expression_t *parse_##unexpression_type(expression_t *left) \
8263 expression_t *unary_expression \
8264 = allocate_expression_zero(unexpression_type); \
8266 unary_expression->unary.value = left; \
8268 sfunc(&unary_expression->unary); \
8270 return unary_expression; \
8273 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8274 EXPR_UNARY_POSTFIX_INCREMENT,
8276 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8277 EXPR_UNARY_POSTFIX_DECREMENT,
8280 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8282 /* TODO: handle complex + imaginary types */
8284 type_left = get_unqualified_type(type_left);
8285 type_right = get_unqualified_type(type_right);
8287 /* § 6.3.1.8 Usual arithmetic conversions */
8288 if (type_left == type_long_double || type_right == type_long_double) {
8289 return type_long_double;
8290 } else if (type_left == type_double || type_right == type_double) {
8292 } else if (type_left == type_float || type_right == type_float) {
8296 type_left = promote_integer(type_left);
8297 type_right = promote_integer(type_right);
8299 if (type_left == type_right)
8302 bool const signed_left = is_type_signed(type_left);
8303 bool const signed_right = is_type_signed(type_right);
8304 int const rank_left = get_rank(type_left);
8305 int const rank_right = get_rank(type_right);
8307 if (signed_left == signed_right)
8308 return rank_left >= rank_right ? type_left : type_right;
8317 u_rank = rank_right;
8318 u_type = type_right;
8320 s_rank = rank_right;
8321 s_type = type_right;
8326 if (u_rank >= s_rank)
8329 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8331 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8332 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8336 case ATOMIC_TYPE_INT: return type_unsigned_int;
8337 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8338 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8340 default: panic("invalid atomic type");
8345 * Check the semantic restrictions for a binary expression.
8347 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8349 expression_t *const left = expression->left;
8350 expression_t *const right = expression->right;
8351 type_t *const orig_type_left = left->base.type;
8352 type_t *const orig_type_right = right->base.type;
8353 type_t *const type_left = skip_typeref(orig_type_left);
8354 type_t *const type_right = skip_typeref(orig_type_right);
8356 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8357 /* TODO: improve error message */
8358 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8359 errorf(&expression->base.source_position,
8360 "operation needs arithmetic types");
8365 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8366 expression->left = create_implicit_cast(left, arithmetic_type);
8367 expression->right = create_implicit_cast(right, arithmetic_type);
8368 expression->base.type = arithmetic_type;
8371 static void warn_div_by_zero(binary_expression_t const *const expression)
8373 if (!warning.div_by_zero ||
8374 !is_type_integer(expression->base.type))
8377 expression_t const *const right = expression->right;
8378 /* The type of the right operand can be different for /= */
8379 if (is_type_integer(right->base.type) &&
8380 is_constant_expression(right) &&
8381 fold_constant(right) == 0) {
8382 warningf(&expression->base.source_position, "division by zero");
8387 * Check the semantic restrictions for a div/mod expression.
8389 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8390 semantic_binexpr_arithmetic(expression);
8391 warn_div_by_zero(expression);
8394 static void semantic_shift_op(binary_expression_t *expression)
8396 expression_t *const left = expression->left;
8397 expression_t *const right = expression->right;
8398 type_t *const orig_type_left = left->base.type;
8399 type_t *const orig_type_right = right->base.type;
8400 type_t * type_left = skip_typeref(orig_type_left);
8401 type_t * type_right = skip_typeref(orig_type_right);
8403 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8404 /* TODO: improve error message */
8405 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8406 errorf(&expression->base.source_position,
8407 "operands of shift operation must have integer types");
8412 type_left = promote_integer(type_left);
8413 type_right = promote_integer(type_right);
8415 expression->left = create_implicit_cast(left, type_left);
8416 expression->right = create_implicit_cast(right, type_right);
8417 expression->base.type = type_left;
8420 static void semantic_add(binary_expression_t *expression)
8422 expression_t *const left = expression->left;
8423 expression_t *const right = expression->right;
8424 type_t *const orig_type_left = left->base.type;
8425 type_t *const orig_type_right = right->base.type;
8426 type_t *const type_left = skip_typeref(orig_type_left);
8427 type_t *const type_right = skip_typeref(orig_type_right);
8430 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8431 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8432 expression->left = create_implicit_cast(left, arithmetic_type);
8433 expression->right = create_implicit_cast(right, arithmetic_type);
8434 expression->base.type = arithmetic_type;
8436 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8437 check_pointer_arithmetic(&expression->base.source_position,
8438 type_left, orig_type_left);
8439 expression->base.type = type_left;
8440 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8441 check_pointer_arithmetic(&expression->base.source_position,
8442 type_right, orig_type_right);
8443 expression->base.type = type_right;
8444 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8445 errorf(&expression->base.source_position,
8446 "invalid operands to binary + ('%T', '%T')",
8447 orig_type_left, orig_type_right);
8451 static void semantic_sub(binary_expression_t *expression)
8453 expression_t *const left = expression->left;
8454 expression_t *const right = expression->right;
8455 type_t *const orig_type_left = left->base.type;
8456 type_t *const orig_type_right = right->base.type;
8457 type_t *const type_left = skip_typeref(orig_type_left);
8458 type_t *const type_right = skip_typeref(orig_type_right);
8459 source_position_t const *const pos = &expression->base.source_position;
8462 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8463 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8464 expression->left = create_implicit_cast(left, arithmetic_type);
8465 expression->right = create_implicit_cast(right, arithmetic_type);
8466 expression->base.type = arithmetic_type;
8468 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8469 check_pointer_arithmetic(&expression->base.source_position,
8470 type_left, orig_type_left);
8471 expression->base.type = type_left;
8472 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8473 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8474 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8475 if (!types_compatible(unqual_left, unqual_right)) {
8477 "subtracting pointers to incompatible types '%T' and '%T'",
8478 orig_type_left, orig_type_right);
8479 } else if (!is_type_object(unqual_left)) {
8480 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8481 errorf(pos, "subtracting pointers to non-object types '%T'",
8483 } else if (warning.other) {
8484 warningf(pos, "subtracting pointers to void");
8487 expression->base.type = type_ptrdiff_t;
8488 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8489 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8490 orig_type_left, orig_type_right);
8494 static void warn_string_literal_address(expression_t const* expr)
8496 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8497 expr = expr->unary.value;
8498 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8500 expr = expr->unary.value;
8503 if (expr->kind == EXPR_STRING_LITERAL ||
8504 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8505 warningf(&expr->base.source_position,
8506 "comparison with string literal results in unspecified behaviour");
8511 * Check the semantics of comparison expressions.
8513 * @param expression The expression to check.
8515 static void semantic_comparison(binary_expression_t *expression)
8517 expression_t *left = expression->left;
8518 expression_t *right = expression->right;
8520 if (warning.address) {
8521 warn_string_literal_address(left);
8522 warn_string_literal_address(right);
8524 expression_t const* const func_left = get_reference_address(left);
8525 if (func_left != NULL && is_null_pointer_constant(right)) {
8526 warningf(&expression->base.source_position,
8527 "the address of '%Y' will never be NULL",
8528 func_left->reference.entity->base.symbol);
8531 expression_t const* const func_right = get_reference_address(right);
8532 if (func_right != NULL && is_null_pointer_constant(right)) {
8533 warningf(&expression->base.source_position,
8534 "the address of '%Y' will never be NULL",
8535 func_right->reference.entity->base.symbol);
8539 type_t *orig_type_left = left->base.type;
8540 type_t *orig_type_right = right->base.type;
8541 type_t *type_left = skip_typeref(orig_type_left);
8542 type_t *type_right = skip_typeref(orig_type_right);
8544 /* TODO non-arithmetic types */
8545 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8546 /* test for signed vs unsigned compares */
8547 if (warning.sign_compare &&
8548 (expression->base.kind != EXPR_BINARY_EQUAL &&
8549 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8550 (is_type_signed(type_left) != is_type_signed(type_right))) {
8552 /* check if 1 of the operands is a constant, in this case we just
8553 * check wether we can safely represent the resulting constant in
8554 * the type of the other operand. */
8555 expression_t *const_expr = NULL;
8556 expression_t *other_expr = NULL;
8558 if (is_constant_expression(left)) {
8561 } else if (is_constant_expression(right)) {
8566 if (const_expr != NULL) {
8567 type_t *other_type = skip_typeref(other_expr->base.type);
8568 long val = fold_constant(const_expr);
8569 /* TODO: check if val can be represented by other_type */
8573 warningf(&expression->base.source_position,
8574 "comparison between signed and unsigned");
8576 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8577 expression->left = create_implicit_cast(left, arithmetic_type);
8578 expression->right = create_implicit_cast(right, arithmetic_type);
8579 expression->base.type = arithmetic_type;
8580 if (warning.float_equal &&
8581 (expression->base.kind == EXPR_BINARY_EQUAL ||
8582 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8583 is_type_float(arithmetic_type)) {
8584 warningf(&expression->base.source_position,
8585 "comparing floating point with == or != is unsafe");
8587 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8588 /* TODO check compatibility */
8589 } else if (is_type_pointer(type_left)) {
8590 expression->right = create_implicit_cast(right, type_left);
8591 } else if (is_type_pointer(type_right)) {
8592 expression->left = create_implicit_cast(left, type_right);
8593 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8594 type_error_incompatible("invalid operands in comparison",
8595 &expression->base.source_position,
8596 type_left, type_right);
8598 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8602 * Checks if a compound type has constant fields.
8604 static bool has_const_fields(const compound_type_t *type)
8606 compound_t *compound = type->compound;
8607 entity_t *entry = compound->members.entities;
8609 for (; entry != NULL; entry = entry->base.next) {
8610 if (!is_declaration(entry))
8613 const type_t *decl_type = skip_typeref(entry->declaration.type);
8614 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8621 static bool is_valid_assignment_lhs(expression_t const* const left)
8623 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8624 type_t *const type_left = skip_typeref(orig_type_left);
8626 if (!is_lvalue(left)) {
8627 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8632 if (is_type_array(type_left)) {
8633 errorf(HERE, "cannot assign to arrays ('%E')", left);
8636 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8637 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8641 if (is_type_incomplete(type_left)) {
8642 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8643 left, orig_type_left);
8646 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8647 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8648 left, orig_type_left);
8655 static void semantic_arithmetic_assign(binary_expression_t *expression)
8657 expression_t *left = expression->left;
8658 expression_t *right = expression->right;
8659 type_t *orig_type_left = left->base.type;
8660 type_t *orig_type_right = right->base.type;
8662 if (!is_valid_assignment_lhs(left))
8665 type_t *type_left = skip_typeref(orig_type_left);
8666 type_t *type_right = skip_typeref(orig_type_right);
8668 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8669 /* TODO: improve error message */
8670 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8671 errorf(&expression->base.source_position,
8672 "operation needs arithmetic types");
8677 /* combined instructions are tricky. We can't create an implicit cast on
8678 * the left side, because we need the uncasted form for the store.
8679 * The ast2firm pass has to know that left_type must be right_type
8680 * for the arithmetic operation and create a cast by itself */
8681 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8682 expression->right = create_implicit_cast(right, arithmetic_type);
8683 expression->base.type = type_left;
8686 static void semantic_divmod_assign(binary_expression_t *expression)
8688 semantic_arithmetic_assign(expression);
8689 warn_div_by_zero(expression);
8692 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8694 expression_t *const left = expression->left;
8695 expression_t *const right = expression->right;
8696 type_t *const orig_type_left = left->base.type;
8697 type_t *const orig_type_right = right->base.type;
8698 type_t *const type_left = skip_typeref(orig_type_left);
8699 type_t *const type_right = skip_typeref(orig_type_right);
8701 if (!is_valid_assignment_lhs(left))
8704 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8705 /* combined instructions are tricky. We can't create an implicit cast on
8706 * the left side, because we need the uncasted form for the store.
8707 * The ast2firm pass has to know that left_type must be right_type
8708 * for the arithmetic operation and create a cast by itself */
8709 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8710 expression->right = create_implicit_cast(right, arithmetic_type);
8711 expression->base.type = type_left;
8712 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8713 check_pointer_arithmetic(&expression->base.source_position,
8714 type_left, orig_type_left);
8715 expression->base.type = type_left;
8716 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8717 errorf(&expression->base.source_position,
8718 "incompatible types '%T' and '%T' in assignment",
8719 orig_type_left, orig_type_right);
8724 * Check the semantic restrictions of a logical expression.
8726 static void semantic_logical_op(binary_expression_t *expression)
8728 expression_t *const left = expression->left;
8729 expression_t *const right = expression->right;
8730 type_t *const orig_type_left = left->base.type;
8731 type_t *const orig_type_right = right->base.type;
8732 type_t *const type_left = skip_typeref(orig_type_left);
8733 type_t *const type_right = skip_typeref(orig_type_right);
8735 warn_function_address_as_bool(left);
8736 warn_function_address_as_bool(right);
8738 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8739 /* TODO: improve error message */
8740 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8741 errorf(&expression->base.source_position,
8742 "operation needs scalar types");
8747 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8751 * Check the semantic restrictions of a binary assign expression.
8753 static void semantic_binexpr_assign(binary_expression_t *expression)
8755 expression_t *left = expression->left;
8756 type_t *orig_type_left = left->base.type;
8758 if (!is_valid_assignment_lhs(left))
8761 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8762 report_assign_error(error, orig_type_left, expression->right,
8763 "assignment", &left->base.source_position);
8764 expression->right = create_implicit_cast(expression->right, orig_type_left);
8765 expression->base.type = orig_type_left;
8769 * Determine if the outermost operation (or parts thereof) of the given
8770 * expression has no effect in order to generate a warning about this fact.
8771 * Therefore in some cases this only examines some of the operands of the
8772 * expression (see comments in the function and examples below).
8774 * f() + 23; // warning, because + has no effect
8775 * x || f(); // no warning, because x controls execution of f()
8776 * x ? y : f(); // warning, because y has no effect
8777 * (void)x; // no warning to be able to suppress the warning
8778 * This function can NOT be used for an "expression has definitely no effect"-
8780 static bool expression_has_effect(const expression_t *const expr)
8782 switch (expr->kind) {
8783 case EXPR_UNKNOWN: break;
8784 case EXPR_INVALID: return true; /* do NOT warn */
8785 case EXPR_REFERENCE: return false;
8786 case EXPR_REFERENCE_ENUM_VALUE: return false;
8787 /* suppress the warning for microsoft __noop operations */
8788 case EXPR_CONST: return expr->conste.is_ms_noop;
8789 case EXPR_CHARACTER_CONSTANT: return false;
8790 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8791 case EXPR_STRING_LITERAL: return false;
8792 case EXPR_WIDE_STRING_LITERAL: return false;
8793 case EXPR_LABEL_ADDRESS: return false;
8796 const call_expression_t *const call = &expr->call;
8797 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8800 switch (call->function->builtin_symbol.symbol->ID) {
8801 case T___builtin_va_end: return true;
8802 default: return false;
8806 /* Generate the warning if either the left or right hand side of a
8807 * conditional expression has no effect */
8808 case EXPR_CONDITIONAL: {
8809 const conditional_expression_t *const cond = &expr->conditional;
8811 expression_has_effect(cond->true_expression) &&
8812 expression_has_effect(cond->false_expression);
8815 case EXPR_SELECT: return false;
8816 case EXPR_ARRAY_ACCESS: return false;
8817 case EXPR_SIZEOF: return false;
8818 case EXPR_CLASSIFY_TYPE: return false;
8819 case EXPR_ALIGNOF: return false;
8821 case EXPR_FUNCNAME: return false;
8822 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8823 case EXPR_BUILTIN_CONSTANT_P: return false;
8824 case EXPR_BUILTIN_PREFETCH: return true;
8825 case EXPR_OFFSETOF: return false;
8826 case EXPR_VA_START: return true;
8827 case EXPR_VA_ARG: return true;
8828 case EXPR_STATEMENT: return true; // TODO
8829 case EXPR_COMPOUND_LITERAL: return false;
8831 case EXPR_UNARY_NEGATE: return false;
8832 case EXPR_UNARY_PLUS: return false;
8833 case EXPR_UNARY_BITWISE_NEGATE: return false;
8834 case EXPR_UNARY_NOT: return false;
8835 case EXPR_UNARY_DEREFERENCE: return false;
8836 case EXPR_UNARY_TAKE_ADDRESS: return false;
8837 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8838 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8839 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8840 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8842 /* Treat void casts as if they have an effect in order to being able to
8843 * suppress the warning */
8844 case EXPR_UNARY_CAST: {
8845 type_t *const type = skip_typeref(expr->base.type);
8846 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8849 case EXPR_UNARY_CAST_IMPLICIT: return true;
8850 case EXPR_UNARY_ASSUME: return true;
8851 case EXPR_UNARY_DELETE: return true;
8852 case EXPR_UNARY_DELETE_ARRAY: return true;
8853 case EXPR_UNARY_THROW: return true;
8855 case EXPR_BINARY_ADD: return false;
8856 case EXPR_BINARY_SUB: return false;
8857 case EXPR_BINARY_MUL: return false;
8858 case EXPR_BINARY_DIV: return false;
8859 case EXPR_BINARY_MOD: return false;
8860 case EXPR_BINARY_EQUAL: return false;
8861 case EXPR_BINARY_NOTEQUAL: return false;
8862 case EXPR_BINARY_LESS: return false;
8863 case EXPR_BINARY_LESSEQUAL: return false;
8864 case EXPR_BINARY_GREATER: return false;
8865 case EXPR_BINARY_GREATEREQUAL: return false;
8866 case EXPR_BINARY_BITWISE_AND: return false;
8867 case EXPR_BINARY_BITWISE_OR: return false;
8868 case EXPR_BINARY_BITWISE_XOR: return false;
8869 case EXPR_BINARY_SHIFTLEFT: return false;
8870 case EXPR_BINARY_SHIFTRIGHT: return false;
8871 case EXPR_BINARY_ASSIGN: return true;
8872 case EXPR_BINARY_MUL_ASSIGN: return true;
8873 case EXPR_BINARY_DIV_ASSIGN: return true;
8874 case EXPR_BINARY_MOD_ASSIGN: return true;
8875 case EXPR_BINARY_ADD_ASSIGN: return true;
8876 case EXPR_BINARY_SUB_ASSIGN: return true;
8877 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8878 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8879 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8880 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8881 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8883 /* Only examine the right hand side of && and ||, because the left hand
8884 * side already has the effect of controlling the execution of the right
8886 case EXPR_BINARY_LOGICAL_AND:
8887 case EXPR_BINARY_LOGICAL_OR:
8888 /* Only examine the right hand side of a comma expression, because the left
8889 * hand side has a separate warning */
8890 case EXPR_BINARY_COMMA:
8891 return expression_has_effect(expr->binary.right);
8893 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8894 case EXPR_BINARY_ISGREATER: return false;
8895 case EXPR_BINARY_ISGREATEREQUAL: return false;
8896 case EXPR_BINARY_ISLESS: return false;
8897 case EXPR_BINARY_ISLESSEQUAL: return false;
8898 case EXPR_BINARY_ISLESSGREATER: return false;
8899 case EXPR_BINARY_ISUNORDERED: return false;
8902 internal_errorf(HERE, "unexpected expression");
8905 static void semantic_comma(binary_expression_t *expression)
8907 if (warning.unused_value) {
8908 const expression_t *const left = expression->left;
8909 if (!expression_has_effect(left)) {
8910 warningf(&left->base.source_position,
8911 "left-hand operand of comma expression has no effect");
8914 expression->base.type = expression->right->base.type;
8918 * @param prec_r precedence of the right operand
8920 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8921 static expression_t *parse_##binexpression_type(expression_t *left) \
8923 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8924 binexpr->binary.left = left; \
8927 expression_t *right = parse_sub_expression(prec_r); \
8929 binexpr->binary.right = right; \
8930 sfunc(&binexpr->binary); \
8935 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8936 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8937 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8938 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8939 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8940 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8941 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8942 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8943 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8944 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8945 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8946 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8947 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8948 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8949 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8950 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8951 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8952 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8953 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8954 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8955 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8956 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8957 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8958 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8959 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8960 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8961 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8962 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8963 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8964 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8967 static expression_t *parse_sub_expression(precedence_t precedence)
8969 if (token.type < 0) {
8970 return expected_expression_error();
8973 expression_parser_function_t *parser
8974 = &expression_parsers[token.type];
8975 source_position_t source_position = token.source_position;
8978 if (parser->parser != NULL) {
8979 left = parser->parser();
8981 left = parse_primary_expression();
8983 assert(left != NULL);
8984 left->base.source_position = source_position;
8987 if (token.type < 0) {
8988 return expected_expression_error();
8991 parser = &expression_parsers[token.type];
8992 if (parser->infix_parser == NULL)
8994 if (parser->infix_precedence < precedence)
8997 left = parser->infix_parser(left);
8999 assert(left != NULL);
9000 assert(left->kind != EXPR_UNKNOWN);
9001 left->base.source_position = source_position;
9008 * Parse an expression.
9010 static expression_t *parse_expression(void)
9012 return parse_sub_expression(PREC_EXPRESSION);
9016 * Register a parser for a prefix-like operator.
9018 * @param parser the parser function
9019 * @param token_type the token type of the prefix token
9021 static void register_expression_parser(parse_expression_function parser,
9024 expression_parser_function_t *entry = &expression_parsers[token_type];
9026 if (entry->parser != NULL) {
9027 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9028 panic("trying to register multiple expression parsers for a token");
9030 entry->parser = parser;
9034 * Register a parser for an infix operator with given precedence.
9036 * @param parser the parser function
9037 * @param token_type the token type of the infix operator
9038 * @param precedence the precedence of the operator
9040 static void register_infix_parser(parse_expression_infix_function parser,
9041 int token_type, unsigned precedence)
9043 expression_parser_function_t *entry = &expression_parsers[token_type];
9045 if (entry->infix_parser != NULL) {
9046 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9047 panic("trying to register multiple infix expression parsers for a "
9050 entry->infix_parser = parser;
9051 entry->infix_precedence = precedence;
9055 * Initialize the expression parsers.
9057 static void init_expression_parsers(void)
9059 memset(&expression_parsers, 0, sizeof(expression_parsers));
9061 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9062 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9063 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9064 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9065 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9066 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9067 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9068 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9069 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9070 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9071 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9072 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9073 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9074 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9075 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9076 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9077 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9078 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9079 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9080 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9081 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9082 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9083 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9084 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9085 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9086 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9087 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9088 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9089 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9090 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9091 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9092 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9093 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9094 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9095 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9096 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9097 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9099 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9100 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9101 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9102 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9103 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9104 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9105 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9106 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9107 register_expression_parser(parse_sizeof, T_sizeof);
9108 register_expression_parser(parse_alignof, T___alignof__);
9109 register_expression_parser(parse_extension, T___extension__);
9110 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9111 register_expression_parser(parse_delete, T_delete);
9112 register_expression_parser(parse_throw, T_throw);
9116 * Parse a asm statement arguments specification.
9118 static asm_argument_t *parse_asm_arguments(bool is_out)
9120 asm_argument_t *result = NULL;
9121 asm_argument_t *last = NULL;
9123 while (token.type == T_STRING_LITERAL || token.type == '[') {
9124 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9125 memset(argument, 0, sizeof(argument[0]));
9127 if (token.type == '[') {
9129 if (token.type != T_IDENTIFIER) {
9130 parse_error_expected("while parsing asm argument",
9131 T_IDENTIFIER, NULL);
9134 argument->symbol = token.v.symbol;
9139 argument->constraints = parse_string_literals();
9141 add_anchor_token(')');
9142 expression_t *expression = parse_expression();
9143 rem_anchor_token(')');
9145 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9146 * change size or type representation (e.g. int -> long is ok, but
9147 * int -> float is not) */
9148 if (expression->kind == EXPR_UNARY_CAST) {
9149 type_t *const type = expression->base.type;
9150 type_kind_t const kind = type->kind;
9151 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9154 if (kind == TYPE_ATOMIC) {
9155 atomic_type_kind_t const akind = type->atomic.akind;
9156 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9157 size = get_atomic_type_size(akind);
9159 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9160 size = get_atomic_type_size(get_intptr_kind());
9164 expression_t *const value = expression->unary.value;
9165 type_t *const value_type = value->base.type;
9166 type_kind_t const value_kind = value_type->kind;
9168 unsigned value_flags;
9169 unsigned value_size;
9170 if (value_kind == TYPE_ATOMIC) {
9171 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9172 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9173 value_size = get_atomic_type_size(value_akind);
9174 } else if (value_kind == TYPE_POINTER) {
9175 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9176 value_size = get_atomic_type_size(get_intptr_kind());
9181 if (value_flags != flags || value_size != size)
9185 } while (expression->kind == EXPR_UNARY_CAST);
9189 if (!is_lvalue(expression)) {
9190 errorf(&expression->base.source_position,
9191 "asm output argument is not an lvalue");
9194 if (argument->constraints.begin[0] == '+')
9195 mark_vars_read(expression, NULL);
9197 mark_vars_read(expression, NULL);
9199 argument->expression = expression;
9202 set_address_taken(expression, true);
9205 last->next = argument;
9211 if (token.type != ',')
9222 * Parse a asm statement clobber specification.
9224 static asm_clobber_t *parse_asm_clobbers(void)
9226 asm_clobber_t *result = NULL;
9227 asm_clobber_t *last = NULL;
9229 while(token.type == T_STRING_LITERAL) {
9230 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9231 clobber->clobber = parse_string_literals();
9234 last->next = clobber;
9240 if (token.type != ',')
9249 * Parse an asm statement.
9251 static statement_t *parse_asm_statement(void)
9253 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9254 asm_statement_t *asm_statement = &statement->asms;
9258 if (token.type == T_volatile) {
9260 asm_statement->is_volatile = true;
9264 add_anchor_token(')');
9265 add_anchor_token(':');
9266 asm_statement->asm_text = parse_string_literals();
9268 if (token.type != ':') {
9269 rem_anchor_token(':');
9274 asm_statement->outputs = parse_asm_arguments(true);
9275 if (token.type != ':') {
9276 rem_anchor_token(':');
9281 asm_statement->inputs = parse_asm_arguments(false);
9282 if (token.type != ':') {
9283 rem_anchor_token(':');
9286 rem_anchor_token(':');
9289 asm_statement->clobbers = parse_asm_clobbers();
9292 rem_anchor_token(')');
9296 if (asm_statement->outputs == NULL) {
9297 /* GCC: An 'asm' instruction without any output operands will be treated
9298 * identically to a volatile 'asm' instruction. */
9299 asm_statement->is_volatile = true;
9304 return create_invalid_statement();
9308 * Parse a case statement.
9310 static statement_t *parse_case_statement(void)
9312 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9313 source_position_t *const pos = &statement->base.source_position;
9317 expression_t *const expression = parse_expression();
9318 statement->case_label.expression = expression;
9319 if (!is_constant_expression(expression)) {
9320 /* This check does not prevent the error message in all cases of an
9321 * prior error while parsing the expression. At least it catches the
9322 * common case of a mistyped enum entry. */
9323 if (is_type_valid(skip_typeref(expression->base.type))) {
9324 errorf(pos, "case label does not reduce to an integer constant");
9326 statement->case_label.is_bad = true;
9328 long const val = fold_constant(expression);
9329 statement->case_label.first_case = val;
9330 statement->case_label.last_case = val;
9334 if (token.type == T_DOTDOTDOT) {
9336 expression_t *const end_range = parse_expression();
9337 statement->case_label.end_range = end_range;
9338 if (!is_constant_expression(end_range)) {
9339 /* This check does not prevent the error message in all cases of an
9340 * prior error while parsing the expression. At least it catches the
9341 * common case of a mistyped enum entry. */
9342 if (is_type_valid(skip_typeref(end_range->base.type))) {
9343 errorf(pos, "case range does not reduce to an integer constant");
9345 statement->case_label.is_bad = true;
9347 long const val = fold_constant(end_range);
9348 statement->case_label.last_case = val;
9350 if (warning.other && val < statement->case_label.first_case) {
9351 statement->case_label.is_empty_range = true;
9352 warningf(pos, "empty range specified");
9358 PUSH_PARENT(statement);
9362 if (current_switch != NULL) {
9363 if (! statement->case_label.is_bad) {
9364 /* Check for duplicate case values */
9365 case_label_statement_t *c = &statement->case_label;
9366 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9367 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9370 if (c->last_case < l->first_case || c->first_case > l->last_case)
9373 errorf(pos, "duplicate case value (previously used %P)",
9374 &l->base.source_position);
9378 /* link all cases into the switch statement */
9379 if (current_switch->last_case == NULL) {
9380 current_switch->first_case = &statement->case_label;
9382 current_switch->last_case->next = &statement->case_label;
9384 current_switch->last_case = &statement->case_label;
9386 errorf(pos, "case label not within a switch statement");
9389 statement_t *const inner_stmt = parse_statement();
9390 statement->case_label.statement = inner_stmt;
9391 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9392 errorf(&inner_stmt->base.source_position, "declaration after case label");
9399 return create_invalid_statement();
9403 * Parse a default statement.
9405 static statement_t *parse_default_statement(void)
9407 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9411 PUSH_PARENT(statement);
9414 if (current_switch != NULL) {
9415 const case_label_statement_t *def_label = current_switch->default_label;
9416 if (def_label != NULL) {
9417 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9418 &def_label->base.source_position);
9420 current_switch->default_label = &statement->case_label;
9422 /* link all cases into the switch statement */
9423 if (current_switch->last_case == NULL) {
9424 current_switch->first_case = &statement->case_label;
9426 current_switch->last_case->next = &statement->case_label;
9428 current_switch->last_case = &statement->case_label;
9431 errorf(&statement->base.source_position,
9432 "'default' label not within a switch statement");
9435 statement_t *const inner_stmt = parse_statement();
9436 statement->case_label.statement = inner_stmt;
9437 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9438 errorf(&inner_stmt->base.source_position, "declaration after default label");
9445 return create_invalid_statement();
9449 * Parse a label statement.
9451 static statement_t *parse_label_statement(void)
9453 assert(token.type == T_IDENTIFIER);
9454 symbol_t *symbol = token.v.symbol;
9455 label_t *label = get_label(symbol);
9457 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9458 statement->label.label = label;
9462 PUSH_PARENT(statement);
9464 /* if statement is already set then the label is defined twice,
9465 * otherwise it was just mentioned in a goto/local label declaration so far
9467 if (label->statement != NULL) {
9468 errorf(HERE, "duplicate label '%Y' (declared %P)",
9469 symbol, &label->base.source_position);
9471 label->base.source_position = token.source_position;
9472 label->statement = statement;
9477 if (token.type == '}') {
9478 /* TODO only warn? */
9479 if (warning.other && false) {
9480 warningf(HERE, "label at end of compound statement");
9481 statement->label.statement = create_empty_statement();
9483 errorf(HERE, "label at end of compound statement");
9484 statement->label.statement = create_invalid_statement();
9486 } else if (token.type == ';') {
9487 /* Eat an empty statement here, to avoid the warning about an empty
9488 * statement after a label. label:; is commonly used to have a label
9489 * before a closing brace. */
9490 statement->label.statement = create_empty_statement();
9493 statement_t *const inner_stmt = parse_statement();
9494 statement->label.statement = inner_stmt;
9495 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9496 errorf(&inner_stmt->base.source_position, "declaration after label");
9500 /* remember the labels in a list for later checking */
9501 if (label_last == NULL) {
9502 label_first = &statement->label;
9504 label_last->next = &statement->label;
9506 label_last = &statement->label;
9513 * Parse an if statement.
9515 static statement_t *parse_if(void)
9517 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9521 PUSH_PARENT(statement);
9523 add_anchor_token('{');
9526 add_anchor_token(')');
9527 expression_t *const expr = parse_expression();
9528 statement->ifs.condition = expr;
9529 mark_vars_read(expr, NULL);
9530 rem_anchor_token(')');
9534 rem_anchor_token('{');
9536 add_anchor_token(T_else);
9537 statement->ifs.true_statement = parse_statement();
9538 rem_anchor_token(T_else);
9540 if (token.type == T_else) {
9542 statement->ifs.false_statement = parse_statement();
9550 * Check that all enums are handled in a switch.
9552 * @param statement the switch statement to check
9554 static void check_enum_cases(const switch_statement_t *statement) {
9555 const type_t *type = skip_typeref(statement->expression->base.type);
9556 if (! is_type_enum(type))
9558 const enum_type_t *enumt = &type->enumt;
9560 /* if we have a default, no warnings */
9561 if (statement->default_label != NULL)
9564 /* FIXME: calculation of value should be done while parsing */
9565 /* TODO: quadratic algorithm here. Change to an n log n one */
9566 long last_value = -1;
9567 const entity_t *entry = enumt->enume->base.next;
9568 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9569 entry = entry->base.next) {
9570 const expression_t *expression = entry->enum_value.value;
9571 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9573 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9574 if (l->expression == NULL)
9576 if (l->first_case <= value && value <= l->last_case) {
9582 warningf(&statement->base.source_position,
9583 "enumeration value '%Y' not handled in switch",
9584 entry->base.symbol);
9591 * Parse a switch statement.
9593 static statement_t *parse_switch(void)
9595 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9599 PUSH_PARENT(statement);
9602 add_anchor_token(')');
9603 expression_t *const expr = parse_expression();
9604 mark_vars_read(expr, NULL);
9605 type_t * type = skip_typeref(expr->base.type);
9606 if (is_type_integer(type)) {
9607 type = promote_integer(type);
9608 if (warning.traditional) {
9609 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9610 warningf(&expr->base.source_position,
9611 "'%T' switch expression not converted to '%T' in ISO C",
9615 } else if (is_type_valid(type)) {
9616 errorf(&expr->base.source_position,
9617 "switch quantity is not an integer, but '%T'", type);
9618 type = type_error_type;
9620 statement->switchs.expression = create_implicit_cast(expr, type);
9622 rem_anchor_token(')');
9624 switch_statement_t *rem = current_switch;
9625 current_switch = &statement->switchs;
9626 statement->switchs.body = parse_statement();
9627 current_switch = rem;
9629 if (warning.switch_default &&
9630 statement->switchs.default_label == NULL) {
9631 warningf(&statement->base.source_position, "switch has no default case");
9633 if (warning.switch_enum)
9634 check_enum_cases(&statement->switchs);
9640 return create_invalid_statement();
9643 static statement_t *parse_loop_body(statement_t *const loop)
9645 statement_t *const rem = current_loop;
9646 current_loop = loop;
9648 statement_t *const body = parse_statement();
9655 * Parse a while statement.
9657 static statement_t *parse_while(void)
9659 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9663 PUSH_PARENT(statement);
9666 add_anchor_token(')');
9667 expression_t *const cond = parse_expression();
9668 statement->whiles.condition = cond;
9669 mark_vars_read(cond, NULL);
9670 rem_anchor_token(')');
9673 statement->whiles.body = parse_loop_body(statement);
9679 return create_invalid_statement();
9683 * Parse a do statement.
9685 static statement_t *parse_do(void)
9687 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9691 PUSH_PARENT(statement);
9693 add_anchor_token(T_while);
9694 statement->do_while.body = parse_loop_body(statement);
9695 rem_anchor_token(T_while);
9699 add_anchor_token(')');
9700 expression_t *const cond = parse_expression();
9701 statement->do_while.condition = cond;
9702 mark_vars_read(cond, NULL);
9703 rem_anchor_token(')');
9711 return create_invalid_statement();
9715 * Parse a for statement.
9717 static statement_t *parse_for(void)
9719 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9723 PUSH_PARENT(statement);
9725 size_t const top = environment_top();
9726 scope_push(&statement->fors.scope);
9729 add_anchor_token(')');
9731 if (token.type != ';') {
9732 if (is_declaration_specifier(&token, false)) {
9733 parse_declaration(record_entity);
9735 add_anchor_token(';');
9736 expression_t *const init = parse_expression();
9737 statement->fors.initialisation = init;
9738 mark_vars_read(init, VAR_ANY);
9739 if (warning.unused_value && !expression_has_effect(init)) {
9740 warningf(&init->base.source_position,
9741 "initialisation of 'for'-statement has no effect");
9743 rem_anchor_token(';');
9750 if (token.type != ';') {
9751 add_anchor_token(';');
9752 expression_t *const cond = parse_expression();
9753 statement->fors.condition = cond;
9754 mark_vars_read(cond, NULL);
9755 rem_anchor_token(';');
9758 if (token.type != ')') {
9759 expression_t *const step = parse_expression();
9760 statement->fors.step = step;
9761 mark_vars_read(step, VAR_ANY);
9762 if (warning.unused_value && !expression_has_effect(step)) {
9763 warningf(&step->base.source_position,
9764 "step of 'for'-statement has no effect");
9768 rem_anchor_token(')');
9769 statement->fors.body = parse_loop_body(statement);
9771 assert(scope == &statement->fors.scope);
9773 environment_pop_to(top);
9780 rem_anchor_token(')');
9781 assert(scope == &statement->fors.scope);
9783 environment_pop_to(top);
9785 return create_invalid_statement();
9789 * Parse a goto statement.
9791 static statement_t *parse_goto(void)
9793 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9796 if (GNU_MODE && token.type == '*') {
9798 expression_t *expression = parse_expression();
9799 mark_vars_read(expression, NULL);
9801 /* Argh: although documentation say the expression must be of type void *,
9802 * gcc excepts anything that can be casted into void * without error */
9803 type_t *type = expression->base.type;
9805 if (type != type_error_type) {
9806 if (!is_type_pointer(type) && !is_type_integer(type)) {
9807 errorf(&expression->base.source_position,
9808 "cannot convert to a pointer type");
9809 } else if (warning.other && type != type_void_ptr) {
9810 warningf(&expression->base.source_position,
9811 "type of computed goto expression should be 'void*' not '%T'", type);
9813 expression = create_implicit_cast(expression, type_void_ptr);
9816 statement->gotos.expression = expression;
9818 if (token.type != T_IDENTIFIER) {
9820 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9822 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9826 symbol_t *symbol = token.v.symbol;
9829 statement->gotos.label = get_label(symbol);
9832 /* remember the goto's in a list for later checking */
9833 if (goto_last == NULL) {
9834 goto_first = &statement->gotos;
9836 goto_last->next = &statement->gotos;
9838 goto_last = &statement->gotos;
9844 return create_invalid_statement();
9848 * Parse a continue statement.
9850 static statement_t *parse_continue(void)
9852 if (current_loop == NULL) {
9853 errorf(HERE, "continue statement not within loop");
9856 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9866 * Parse a break statement.
9868 static statement_t *parse_break(void)
9870 if (current_switch == NULL && current_loop == NULL) {
9871 errorf(HERE, "break statement not within loop or switch");
9874 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9884 * Parse a __leave statement.
9886 static statement_t *parse_leave_statement(void)
9888 if (current_try == NULL) {
9889 errorf(HERE, "__leave statement not within __try");
9892 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9902 * Check if a given entity represents a local variable.
9904 static bool is_local_variable(const entity_t *entity)
9906 if (entity->kind != ENTITY_VARIABLE)
9909 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9910 case STORAGE_CLASS_AUTO:
9911 case STORAGE_CLASS_REGISTER: {
9912 const type_t *type = skip_typeref(entity->declaration.type);
9913 if (is_type_function(type)) {
9925 * Check if a given expression represents a local variable.
9927 static bool expression_is_local_variable(const expression_t *expression)
9929 if (expression->base.kind != EXPR_REFERENCE) {
9932 const entity_t *entity = expression->reference.entity;
9933 return is_local_variable(entity);
9937 * Check if a given expression represents a local variable and
9938 * return its declaration then, else return NULL.
9940 entity_t *expression_is_variable(const expression_t *expression)
9942 if (expression->base.kind != EXPR_REFERENCE) {
9945 entity_t *entity = expression->reference.entity;
9946 if (entity->kind != ENTITY_VARIABLE)
9953 * Parse a return statement.
9955 static statement_t *parse_return(void)
9959 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9961 expression_t *return_value = NULL;
9962 if (token.type != ';') {
9963 return_value = parse_expression();
9964 mark_vars_read(return_value, NULL);
9967 const type_t *const func_type = current_function->base.type;
9968 assert(is_type_function(func_type));
9969 type_t *const return_type = skip_typeref(func_type->function.return_type);
9971 if (return_value != NULL) {
9972 type_t *return_value_type = skip_typeref(return_value->base.type);
9974 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
9975 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9976 if (warning.other) {
9977 warningf(&statement->base.source_position,
9978 "'return' with a value, in function returning void");
9980 return_value = NULL;
9982 assign_error_t error = semantic_assign(return_type, return_value);
9983 report_assign_error(error, return_type, return_value, "'return'",
9984 &statement->base.source_position);
9985 return_value = create_implicit_cast(return_value, return_type);
9987 /* check for returning address of a local var */
9988 if (warning.other && return_value != NULL
9989 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9990 const expression_t *expression = return_value->unary.value;
9991 if (expression_is_local_variable(expression)) {
9992 warningf(&statement->base.source_position,
9993 "function returns address of local variable");
9996 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9997 warningf(&statement->base.source_position,
9998 "'return' without value, in function returning non-void");
10000 statement->returns.value = return_value;
10009 * Parse a declaration statement.
10011 static statement_t *parse_declaration_statement(void)
10013 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10015 entity_t *before = scope->last_entity;
10017 parse_external_declaration();
10019 parse_declaration(record_entity);
10021 if (before == NULL) {
10022 statement->declaration.declarations_begin = scope->entities;
10024 statement->declaration.declarations_begin = before->base.next;
10026 statement->declaration.declarations_end = scope->last_entity;
10032 * Parse an expression statement, ie. expr ';'.
10034 static statement_t *parse_expression_statement(void)
10036 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10038 expression_t *const expr = parse_expression();
10039 statement->expression.expression = expr;
10040 mark_vars_read(expr, VAR_ANY);
10049 * Parse a microsoft __try { } __finally { } or
10050 * __try{ } __except() { }
10052 static statement_t *parse_ms_try_statment(void)
10054 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10057 PUSH_PARENT(statement);
10059 ms_try_statement_t *rem = current_try;
10060 current_try = &statement->ms_try;
10061 statement->ms_try.try_statement = parse_compound_statement(false);
10066 if (token.type == T___except) {
10069 add_anchor_token(')');
10070 expression_t *const expr = parse_expression();
10071 mark_vars_read(expr, NULL);
10072 type_t * type = skip_typeref(expr->base.type);
10073 if (is_type_integer(type)) {
10074 type = promote_integer(type);
10075 } else if (is_type_valid(type)) {
10076 errorf(&expr->base.source_position,
10077 "__expect expression is not an integer, but '%T'", type);
10078 type = type_error_type;
10080 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10081 rem_anchor_token(')');
10083 statement->ms_try.final_statement = parse_compound_statement(false);
10084 } else if (token.type == T__finally) {
10086 statement->ms_try.final_statement = parse_compound_statement(false);
10088 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10089 return create_invalid_statement();
10093 return create_invalid_statement();
10096 static statement_t *parse_empty_statement(void)
10098 if (warning.empty_statement) {
10099 warningf(HERE, "statement is empty");
10101 statement_t *const statement = create_empty_statement();
10106 static statement_t *parse_local_label_declaration(void)
10108 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10112 entity_t *begin = NULL, *end = NULL;
10115 if (token.type != T_IDENTIFIER) {
10116 parse_error_expected("while parsing local label declaration",
10117 T_IDENTIFIER, NULL);
10120 symbol_t *symbol = token.v.symbol;
10121 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10122 if (entity != NULL && entity->base.parent_scope == scope) {
10123 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10124 symbol, &entity->base.source_position);
10126 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10128 entity->base.parent_scope = scope;
10129 entity->base.namespc = NAMESPACE_LABEL;
10130 entity->base.source_position = token.source_position;
10131 entity->base.symbol = symbol;
10134 end->base.next = entity;
10139 environment_push(entity);
10143 if (token.type != ',')
10149 statement->declaration.declarations_begin = begin;
10150 statement->declaration.declarations_end = end;
10155 * Parse a statement.
10156 * There's also parse_statement() which additionally checks for
10157 * "statement has no effect" warnings
10159 static statement_t *intern_parse_statement(void)
10161 statement_t *statement = NULL;
10163 /* declaration or statement */
10164 add_anchor_token(';');
10165 switch (token.type) {
10166 case T_IDENTIFIER: {
10167 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10168 if (la1_type == ':') {
10169 statement = parse_label_statement();
10170 } else if (is_typedef_symbol(token.v.symbol)) {
10171 statement = parse_declaration_statement();
10173 /* it's an identifier, the grammar says this must be an
10174 * expression statement. However it is common that users mistype
10175 * declaration types, so we guess a bit here to improve robustness
10176 * for incorrect programs */
10177 switch (la1_type) {
10179 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10180 goto expression_statment;
10185 statement = parse_declaration_statement();
10189 expression_statment:
10190 statement = parse_expression_statement();
10197 case T___extension__:
10198 /* This can be a prefix to a declaration or an expression statement.
10199 * We simply eat it now and parse the rest with tail recursion. */
10202 } while (token.type == T___extension__);
10203 bool old_gcc_extension = in_gcc_extension;
10204 in_gcc_extension = true;
10205 statement = parse_statement();
10206 in_gcc_extension = old_gcc_extension;
10210 statement = parse_declaration_statement();
10214 statement = parse_local_label_declaration();
10217 case ';': statement = parse_empty_statement(); break;
10218 case '{': statement = parse_compound_statement(false); break;
10219 case T___leave: statement = parse_leave_statement(); break;
10220 case T___try: statement = parse_ms_try_statment(); break;
10221 case T_asm: statement = parse_asm_statement(); break;
10222 case T_break: statement = parse_break(); break;
10223 case T_case: statement = parse_case_statement(); break;
10224 case T_continue: statement = parse_continue(); break;
10225 case T_default: statement = parse_default_statement(); break;
10226 case T_do: statement = parse_do(); break;
10227 case T_for: statement = parse_for(); break;
10228 case T_goto: statement = parse_goto(); break;
10229 case T_if: statement = parse_if(); break;
10230 case T_return: statement = parse_return(); break;
10231 case T_switch: statement = parse_switch(); break;
10232 case T_while: statement = parse_while(); break;
10235 statement = parse_expression_statement();
10239 errorf(HERE, "unexpected token %K while parsing statement", &token);
10240 statement = create_invalid_statement();
10245 rem_anchor_token(';');
10247 assert(statement != NULL
10248 && statement->base.source_position.input_name != NULL);
10254 * parse a statement and emits "statement has no effect" warning if needed
10255 * (This is really a wrapper around intern_parse_statement with check for 1
10256 * single warning. It is needed, because for statement expressions we have
10257 * to avoid the warning on the last statement)
10259 static statement_t *parse_statement(void)
10261 statement_t *statement = intern_parse_statement();
10263 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10264 expression_t *expression = statement->expression.expression;
10265 if (!expression_has_effect(expression)) {
10266 warningf(&expression->base.source_position,
10267 "statement has no effect");
10275 * Parse a compound statement.
10277 static statement_t *parse_compound_statement(bool inside_expression_statement)
10279 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10281 PUSH_PARENT(statement);
10284 add_anchor_token('}');
10286 size_t const top = environment_top();
10287 scope_push(&statement->compound.scope);
10289 statement_t **anchor = &statement->compound.statements;
10290 bool only_decls_so_far = true;
10291 while (token.type != '}') {
10292 if (token.type == T_EOF) {
10293 errorf(&statement->base.source_position,
10294 "EOF while parsing compound statement");
10297 statement_t *sub_statement = intern_parse_statement();
10298 if (is_invalid_statement(sub_statement)) {
10299 /* an error occurred. if we are at an anchor, return */
10305 if (warning.declaration_after_statement) {
10306 if (sub_statement->kind != STATEMENT_DECLARATION) {
10307 only_decls_so_far = false;
10308 } else if (!only_decls_so_far) {
10309 warningf(&sub_statement->base.source_position,
10310 "ISO C90 forbids mixed declarations and code");
10314 *anchor = sub_statement;
10316 while (sub_statement->base.next != NULL)
10317 sub_statement = sub_statement->base.next;
10319 anchor = &sub_statement->base.next;
10323 /* look over all statements again to produce no effect warnings */
10324 if (warning.unused_value) {
10325 statement_t *sub_statement = statement->compound.statements;
10326 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10327 if (sub_statement->kind != STATEMENT_EXPRESSION)
10329 /* don't emit a warning for the last expression in an expression
10330 * statement as it has always an effect */
10331 if (inside_expression_statement && sub_statement->base.next == NULL)
10334 expression_t *expression = sub_statement->expression.expression;
10335 if (!expression_has_effect(expression)) {
10336 warningf(&expression->base.source_position,
10337 "statement has no effect");
10343 rem_anchor_token('}');
10344 assert(scope == &statement->compound.scope);
10346 environment_pop_to(top);
10353 * Initialize builtin types.
10355 static void initialize_builtin_types(void)
10357 type_intmax_t = make_global_typedef("__intmax_t__", type_long_long);
10358 type_size_t = make_global_typedef("__SIZE_TYPE__", type_unsigned_long);
10359 type_ssize_t = make_global_typedef("__SSIZE_TYPE__", type_long);
10360 type_ptrdiff_t = make_global_typedef("__PTRDIFF_TYPE__", type_long);
10361 type_uintmax_t = make_global_typedef("__uintmax_t__", type_unsigned_long_long);
10362 type_uptrdiff_t = make_global_typedef("__UPTRDIFF_TYPE__", type_unsigned_long);
10363 type_wchar_t = make_global_typedef("__WCHAR_TYPE__", opt_short_wchar_t ? type_unsigned_short : type_int);
10364 type_wint_t = make_global_typedef("__WINT_TYPE__", type_int);
10366 type_intmax_t_ptr = make_pointer_type(type_intmax_t, TYPE_QUALIFIER_NONE);
10367 type_ptrdiff_t_ptr = make_pointer_type(type_ptrdiff_t, TYPE_QUALIFIER_NONE);
10368 type_ssize_t_ptr = make_pointer_type(type_ssize_t, TYPE_QUALIFIER_NONE);
10369 type_wchar_t_ptr = make_pointer_type(type_wchar_t, TYPE_QUALIFIER_NONE);
10371 /* const version of wchar_t */
10372 type_const_wchar_t = allocate_type_zero(TYPE_TYPEDEF);
10373 type_const_wchar_t->typedeft.typedefe = type_wchar_t->typedeft.typedefe;
10374 type_const_wchar_t->base.qualifiers |= TYPE_QUALIFIER_CONST;
10376 type_const_wchar_t_ptr = make_pointer_type(type_const_wchar_t, TYPE_QUALIFIER_NONE);
10380 * Check for unused global static functions and variables
10382 static void check_unused_globals(void)
10384 if (!warning.unused_function && !warning.unused_variable)
10387 for (const entity_t *entity = file_scope->entities; entity != NULL;
10388 entity = entity->base.next) {
10389 if (!is_declaration(entity))
10392 const declaration_t *declaration = &entity->declaration;
10393 if (declaration->used ||
10394 declaration->modifiers & DM_UNUSED ||
10395 declaration->modifiers & DM_USED ||
10396 declaration->storage_class != STORAGE_CLASS_STATIC)
10399 type_t *const type = declaration->type;
10401 if (entity->kind == ENTITY_FUNCTION) {
10402 /* inhibit warning for static inline functions */
10403 if (entity->function.is_inline)
10406 s = entity->function.statement != NULL ? "defined" : "declared";
10411 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10412 type, declaration->base.symbol, s);
10416 static void parse_global_asm(void)
10418 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10423 statement->asms.asm_text = parse_string_literals();
10424 statement->base.next = unit->global_asm;
10425 unit->global_asm = statement;
10434 * Parse a translation unit.
10436 static void parse_translation_unit(void)
10438 add_anchor_token(T_EOF);
10441 unsigned char token_anchor_copy[T_LAST_TOKEN];
10442 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10446 bool anchor_leak = false;
10447 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10448 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10450 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10451 anchor_leak = true;
10454 if (in_gcc_extension) {
10455 errorf(HERE, "Leaked __extension__");
10456 anchor_leak = true;
10463 switch (token.type) {
10466 case T___extension__:
10467 parse_external_declaration();
10471 parse_global_asm();
10475 rem_anchor_token(T_EOF);
10479 if (!strict_mode) {
10481 warningf(HERE, "stray ';' outside of function");
10488 errorf(HERE, "stray %K outside of function", &token);
10489 if (token.type == '(' || token.type == '{' || token.type == '[')
10490 eat_until_matching_token(token.type);
10500 * @return the translation unit or NULL if errors occurred.
10502 void start_parsing(void)
10504 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10505 label_stack = NEW_ARR_F(stack_entry_t, 0);
10506 diagnostic_count = 0;
10510 type_set_output(stderr);
10511 ast_set_output(stderr);
10513 assert(unit == NULL);
10514 unit = allocate_ast_zero(sizeof(unit[0]));
10516 assert(file_scope == NULL);
10517 file_scope = &unit->scope;
10519 assert(scope == NULL);
10520 scope_push(&unit->scope);
10522 initialize_builtin_types();
10525 translation_unit_t *finish_parsing(void)
10527 /* do NOT use scope_pop() here, this will crash, will it by hand */
10528 assert(scope == &unit->scope);
10531 assert(file_scope == &unit->scope);
10532 check_unused_globals();
10535 DEL_ARR_F(environment_stack);
10536 DEL_ARR_F(label_stack);
10538 translation_unit_t *result = unit;
10545 lookahead_bufpos = 0;
10546 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10549 parse_translation_unit();
10553 * Initialize the parser.
10555 void init_parser(void)
10557 sym_anonymous = symbol_table_insert("<anonymous>");
10559 if (c_mode & _MS) {
10560 /* add predefined symbols for extended-decl-modifier */
10561 sym_align = symbol_table_insert("align");
10562 sym_allocate = symbol_table_insert("allocate");
10563 sym_dllimport = symbol_table_insert("dllimport");
10564 sym_dllexport = symbol_table_insert("dllexport");
10565 sym_naked = symbol_table_insert("naked");
10566 sym_noinline = symbol_table_insert("noinline");
10567 sym_noreturn = symbol_table_insert("noreturn");
10568 sym_nothrow = symbol_table_insert("nothrow");
10569 sym_novtable = symbol_table_insert("novtable");
10570 sym_property = symbol_table_insert("property");
10571 sym_get = symbol_table_insert("get");
10572 sym_put = symbol_table_insert("put");
10573 sym_selectany = symbol_table_insert("selectany");
10574 sym_thread = symbol_table_insert("thread");
10575 sym_uuid = symbol_table_insert("uuid");
10576 sym_deprecated = symbol_table_insert("deprecated");
10577 sym_restrict = symbol_table_insert("restrict");
10578 sym_noalias = symbol_table_insert("noalias");
10580 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10582 init_expression_parsers();
10583 obstack_init(&temp_obst);
10585 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10586 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10590 * Terminate the parser.
10592 void exit_parser(void)
10594 obstack_free(&temp_obst, NULL);