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 string_t parse_string_literals(void)
1168 assert(token.type == T_STRING_LITERAL);
1169 string_t result = token.v.string;
1173 while (token.type == T_STRING_LITERAL) {
1174 result = concat_strings(&result, &token.v.string);
1181 static const char *const gnu_attribute_names[GNU_AK_LAST] = {
1182 [GNU_AK_CONST] = "const",
1183 [GNU_AK_VOLATILE] = "volatile",
1184 [GNU_AK_CDECL] = "cdecl",
1185 [GNU_AK_STDCALL] = "stdcall",
1186 [GNU_AK_FASTCALL] = "fastcall",
1187 [GNU_AK_DEPRECATED] = "deprecated",
1188 [GNU_AK_NOINLINE] = "noinline",
1189 [GNU_AK_NORETURN] = "noreturn",
1190 [GNU_AK_NAKED] = "naked",
1191 [GNU_AK_PURE] = "pure",
1192 [GNU_AK_ALWAYS_INLINE] = "always_inline",
1193 [GNU_AK_MALLOC] = "malloc",
1194 [GNU_AK_WEAK] = "weak",
1195 [GNU_AK_CONSTRUCTOR] = "constructor",
1196 [GNU_AK_DESTRUCTOR] = "destructor",
1197 [GNU_AK_NOTHROW] = "nothrow",
1198 [GNU_AK_TRANSPARENT_UNION] = "transparent_union",
1199 [GNU_AK_COMMON] = "common",
1200 [GNU_AK_NOCOMMON] = "nocommon",
1201 [GNU_AK_PACKED] = "packed",
1202 [GNU_AK_SHARED] = "shared",
1203 [GNU_AK_NOTSHARED] = "notshared",
1204 [GNU_AK_USED] = "used",
1205 [GNU_AK_UNUSED] = "unused",
1206 [GNU_AK_NO_INSTRUMENT_FUNCTION] = "no_instrument_function",
1207 [GNU_AK_WARN_UNUSED_RESULT] = "warn_unused_result",
1208 [GNU_AK_LONGCALL] = "longcall",
1209 [GNU_AK_SHORTCALL] = "shortcall",
1210 [GNU_AK_LONG_CALL] = "long_call",
1211 [GNU_AK_SHORT_CALL] = "short_call",
1212 [GNU_AK_FUNCTION_VECTOR] = "function_vector",
1213 [GNU_AK_INTERRUPT] = "interrupt",
1214 [GNU_AK_INTERRUPT_HANDLER] = "interrupt_handler",
1215 [GNU_AK_NMI_HANDLER] = "nmi_handler",
1216 [GNU_AK_NESTING] = "nesting",
1217 [GNU_AK_NEAR] = "near",
1218 [GNU_AK_FAR] = "far",
1219 [GNU_AK_SIGNAL] = "signal",
1220 [GNU_AK_EIGTHBIT_DATA] = "eightbit_data",
1221 [GNU_AK_TINY_DATA] = "tiny_data",
1222 [GNU_AK_SAVEALL] = "saveall",
1223 [GNU_AK_FLATTEN] = "flatten",
1224 [GNU_AK_SSEREGPARM] = "sseregparm",
1225 [GNU_AK_EXTERNALLY_VISIBLE] = "externally_visible",
1226 [GNU_AK_RETURN_TWICE] = "return_twice",
1227 [GNU_AK_MAY_ALIAS] = "may_alias",
1228 [GNU_AK_MS_STRUCT] = "ms_struct",
1229 [GNU_AK_GCC_STRUCT] = "gcc_struct",
1230 [GNU_AK_DLLIMPORT] = "dllimport",
1231 [GNU_AK_DLLEXPORT] = "dllexport",
1232 [GNU_AK_ALIGNED] = "aligned",
1233 [GNU_AK_ALIAS] = "alias",
1234 [GNU_AK_SECTION] = "section",
1235 [GNU_AK_FORMAT] = "format",
1236 [GNU_AK_FORMAT_ARG] = "format_arg",
1237 [GNU_AK_WEAKREF] = "weakref",
1238 [GNU_AK_NONNULL] = "nonnull",
1239 [GNU_AK_TLS_MODEL] = "tls_model",
1240 [GNU_AK_VISIBILITY] = "visibility",
1241 [GNU_AK_REGPARM] = "regparm",
1242 [GNU_AK_MODE] = "mode",
1243 [GNU_AK_MODEL] = "model",
1244 [GNU_AK_TRAP_EXIT] = "trap_exit",
1245 [GNU_AK_SP_SWITCH] = "sp_switch",
1246 [GNU_AK_SENTINEL] = "sentinel"
1250 * compare two string, ignoring double underscores on the second.
1252 static int strcmp_underscore(const char *s1, const char *s2)
1254 if (s2[0] == '_' && s2[1] == '_') {
1255 size_t len2 = strlen(s2);
1256 size_t len1 = strlen(s1);
1257 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1258 return strncmp(s1, s2+2, len2-4);
1262 return strcmp(s1, s2);
1266 * Allocate a new gnu temporal attribute.
1268 static gnu_attribute_t *allocate_gnu_attribute(gnu_attribute_kind_t kind)
1270 gnu_attribute_t *attribute = obstack_alloc(&temp_obst, sizeof(*attribute));
1271 attribute->kind = kind;
1272 attribute->next = NULL;
1273 attribute->invalid = false;
1274 attribute->have_arguments = false;
1280 * parse one constant expression argument.
1282 static void parse_gnu_attribute_const_arg(gnu_attribute_t *attribute)
1284 expression_t *expression;
1285 add_anchor_token(')');
1286 expression = parse_constant_expression();
1287 rem_anchor_token(')');
1289 attribute->u.argument = fold_constant(expression);
1292 attribute->invalid = true;
1296 * parse a list of constant expressions arguments.
1298 static void parse_gnu_attribute_const_arg_list(gnu_attribute_t *attribute)
1300 argument_list_t **list = &attribute->u.arguments;
1301 argument_list_t *entry;
1302 expression_t *expression;
1303 add_anchor_token(')');
1304 add_anchor_token(',');
1306 expression = parse_constant_expression();
1307 entry = obstack_alloc(&temp_obst, sizeof(entry));
1308 entry->argument = fold_constant(expression);
1311 list = &entry->next;
1312 if (token.type != ',')
1316 rem_anchor_token(',');
1317 rem_anchor_token(')');
1321 attribute->invalid = true;
1325 * parse one string literal argument.
1327 static void parse_gnu_attribute_string_arg(gnu_attribute_t *attribute,
1330 add_anchor_token('(');
1331 if (token.type != T_STRING_LITERAL) {
1332 parse_error_expected("while parsing attribute directive",
1333 T_STRING_LITERAL, NULL);
1336 *string = parse_string_literals();
1337 rem_anchor_token('(');
1341 attribute->invalid = true;
1345 * parse one tls model.
1347 static void parse_gnu_attribute_tls_model_arg(gnu_attribute_t *attribute)
1349 static const char *const tls_models[] = {
1355 string_t string = { NULL, 0 };
1356 parse_gnu_attribute_string_arg(attribute, &string);
1357 if (string.begin != NULL) {
1358 for(size_t i = 0; i < 4; ++i) {
1359 if (strcmp(tls_models[i], string.begin) == 0) {
1360 attribute->u.value = i;
1364 errorf(HERE, "'%s' is an unrecognized tls model", string.begin);
1366 attribute->invalid = true;
1370 * parse one tls model.
1372 static void parse_gnu_attribute_visibility_arg(gnu_attribute_t *attribute)
1374 static const char *const visibilities[] = {
1380 string_t string = { NULL, 0 };
1381 parse_gnu_attribute_string_arg(attribute, &string);
1382 if (string.begin != NULL) {
1383 for(size_t i = 0; i < 4; ++i) {
1384 if (strcmp(visibilities[i], string.begin) == 0) {
1385 attribute->u.value = i;
1389 errorf(HERE, "'%s' is an unrecognized visibility", string.begin);
1391 attribute->invalid = true;
1395 * parse one (code) model.
1397 static void parse_gnu_attribute_model_arg(gnu_attribute_t *attribute)
1399 static const char *const visibilities[] = {
1404 string_t string = { NULL, 0 };
1405 parse_gnu_attribute_string_arg(attribute, &string);
1406 if (string.begin != NULL) {
1407 for(int i = 0; i < 3; ++i) {
1408 if (strcmp(visibilities[i], string.begin) == 0) {
1409 attribute->u.value = i;
1413 errorf(HERE, "'%s' is an unrecognized model", string.begin);
1415 attribute->invalid = true;
1418 static void parse_gnu_attribute_mode_arg(gnu_attribute_t *attribute)
1420 /* TODO: find out what is allowed here... */
1422 /* at least: byte, word, pointer, list of machine modes
1423 * __XXX___ is interpreted as XXX */
1424 add_anchor_token(')');
1426 if (token.type != T_IDENTIFIER) {
1427 expect(T_IDENTIFIER);
1430 /* This isn't really correct, the backend should provide a list of machine
1431 * specific modes (according to gcc philosophy that is...) */
1432 const char *symbol_str = token.v.symbol->string;
1433 if (strcmp_underscore("QI", symbol_str) == 0 ||
1434 strcmp_underscore("byte", symbol_str) == 0) {
1435 attribute->u.akind = ATOMIC_TYPE_CHAR;
1436 } else if (strcmp_underscore("HI", symbol_str) == 0) {
1437 attribute->u.akind = ATOMIC_TYPE_SHORT;
1438 } else if (strcmp_underscore("SI", symbol_str) == 0
1439 || strcmp_underscore("word", symbol_str) == 0
1440 || strcmp_underscore("pointer", symbol_str) == 0) {
1441 attribute->u.akind = ATOMIC_TYPE_INT;
1442 } else if (strcmp_underscore("DI", symbol_str) == 0) {
1443 attribute->u.akind = ATOMIC_TYPE_LONGLONG;
1446 warningf(HERE, "ignoring unknown mode '%s'", symbol_str);
1447 attribute->invalid = true;
1451 rem_anchor_token(')');
1455 attribute->invalid = true;
1459 * parse one interrupt argument.
1461 static void parse_gnu_attribute_interrupt_arg(gnu_attribute_t *attribute)
1463 static const char *const interrupts[] = {
1470 string_t string = { NULL, 0 };
1471 parse_gnu_attribute_string_arg(attribute, &string);
1472 if (string.begin != NULL) {
1473 for(size_t i = 0; i < 5; ++i) {
1474 if (strcmp(interrupts[i], string.begin) == 0) {
1475 attribute->u.value = i;
1479 errorf(HERE, "'%s' is not an interrupt", string.begin);
1481 attribute->invalid = true;
1485 * parse ( identifier, const expression, const expression )
1487 static void parse_gnu_attribute_format_args(gnu_attribute_t *attribute)
1489 static const char *const format_names[] = {
1497 if (token.type != T_IDENTIFIER) {
1498 parse_error_expected("while parsing format attribute directive", T_IDENTIFIER, NULL);
1501 const char *name = token.v.symbol->string;
1502 for(i = 0; i < 4; ++i) {
1503 if (strcmp_underscore(format_names[i], name) == 0)
1507 if (warning.attribute)
1508 warningf(HERE, "'%s' is an unrecognized format function type", name);
1513 add_anchor_token(')');
1514 add_anchor_token(',');
1515 parse_constant_expression();
1516 rem_anchor_token(',');
1517 rem_anchor_token(')');
1520 add_anchor_token(')');
1521 parse_constant_expression();
1522 rem_anchor_token(')');
1526 attribute->u.value = true;
1529 static void check_no_argument(gnu_attribute_t *attribute, const char *name)
1531 if (!attribute->have_arguments)
1534 /* should have no arguments */
1535 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1536 eat_until_matching_token('(');
1537 /* we have already consumed '(', so we stop before ')', eat it */
1539 attribute->invalid = true;
1543 * Parse one GNU attribute.
1545 * Note that attribute names can be specified WITH or WITHOUT
1546 * double underscores, ie const or __const__.
1548 * The following attributes are parsed without arguments
1573 * no_instrument_function
1574 * warn_unused_result
1591 * externally_visible
1599 * The following attributes are parsed with arguments
1600 * aligned( const expression )
1601 * alias( string literal )
1602 * section( string literal )
1603 * format( identifier, const expression, const expression )
1604 * format_arg( const expression )
1605 * tls_model( string literal )
1606 * visibility( string literal )
1607 * regparm( const expression )
1608 * model( string leteral )
1609 * trap_exit( const expression )
1610 * sp_switch( string literal )
1612 * The following attributes might have arguments
1613 * weak_ref( string literal )
1614 * non_null( const expression // ',' )
1615 * interrupt( string literal )
1616 * sentinel( constant expression )
1618 static decl_modifiers_t parse_gnu_attribute(gnu_attribute_t **attributes)
1620 gnu_attribute_t *head = *attributes;
1621 gnu_attribute_t *last = *attributes;
1622 decl_modifiers_t modifiers = 0;
1623 gnu_attribute_t *attribute;
1625 eat(T___attribute__);
1629 if (token.type != ')') {
1630 /* find the end of the list */
1632 while (last->next != NULL)
1636 /* non-empty attribute list */
1639 if (token.type == T_const) {
1641 } else if (token.type == T_volatile) {
1643 } else if (token.type == T_cdecl) {
1644 /* __attribute__((cdecl)), WITH ms mode */
1646 } else if (token.type == T_IDENTIFIER) {
1647 const symbol_t *sym = token.v.symbol;
1650 parse_error_expected("while parsing GNU attribute", T_IDENTIFIER, NULL);
1657 for(i = 0; i < GNU_AK_LAST; ++i) {
1658 if (strcmp_underscore(gnu_attribute_names[i], name) == 0)
1661 gnu_attribute_kind_t kind = (gnu_attribute_kind_t)i;
1664 if (kind == GNU_AK_LAST) {
1665 if (warning.attribute)
1666 warningf(HERE, "'%s' attribute directive ignored", name);
1668 /* skip possible arguments */
1669 if (token.type == '(') {
1670 eat_until_matching_token(')');
1673 /* check for arguments */
1674 attribute = allocate_gnu_attribute(kind);
1675 if (token.type == '(') {
1677 if (token.type == ')') {
1678 /* empty args are allowed */
1681 attribute->have_arguments = true;
1685 case GNU_AK_VOLATILE:
1690 case GNU_AK_NOCOMMON:
1692 case GNU_AK_NOTSHARED:
1693 case GNU_AK_NO_INSTRUMENT_FUNCTION:
1694 case GNU_AK_WARN_UNUSED_RESULT:
1695 case GNU_AK_LONGCALL:
1696 case GNU_AK_SHORTCALL:
1697 case GNU_AK_LONG_CALL:
1698 case GNU_AK_SHORT_CALL:
1699 case GNU_AK_FUNCTION_VECTOR:
1700 case GNU_AK_INTERRUPT_HANDLER:
1701 case GNU_AK_NMI_HANDLER:
1702 case GNU_AK_NESTING:
1706 case GNU_AK_EIGTHBIT_DATA:
1707 case GNU_AK_TINY_DATA:
1708 case GNU_AK_SAVEALL:
1709 case GNU_AK_FLATTEN:
1710 case GNU_AK_SSEREGPARM:
1711 case GNU_AK_EXTERNALLY_VISIBLE:
1712 case GNU_AK_RETURN_TWICE:
1713 case GNU_AK_MAY_ALIAS:
1714 case GNU_AK_MS_STRUCT:
1715 case GNU_AK_GCC_STRUCT:
1718 case GNU_AK_CDECL: modifiers |= DM_CDECL; goto no_arg;
1719 case GNU_AK_FASTCALL: modifiers |= DM_FASTCALL; goto no_arg;
1720 case GNU_AK_STDCALL: modifiers |= DM_STDCALL; goto no_arg;
1721 case GNU_AK_UNUSED: modifiers |= DM_UNUSED; goto no_arg;
1722 case GNU_AK_USED: modifiers |= DM_USED; goto no_arg;
1723 case GNU_AK_PURE: modifiers |= DM_PURE; goto no_arg;
1724 case GNU_AK_CONST: modifiers |= DM_CONST; goto no_arg;
1725 case GNU_AK_ALWAYS_INLINE: modifiers |= DM_FORCEINLINE; goto no_arg;
1726 case GNU_AK_DLLIMPORT: modifiers |= DM_DLLIMPORT; goto no_arg;
1727 case GNU_AK_DLLEXPORT: modifiers |= DM_DLLEXPORT; goto no_arg;
1728 case GNU_AK_PACKED: modifiers |= DM_PACKED; goto no_arg;
1729 case GNU_AK_NOINLINE: modifiers |= DM_NOINLINE; goto no_arg;
1730 case GNU_AK_NORETURN: modifiers |= DM_NORETURN; goto no_arg;
1731 case GNU_AK_NOTHROW: modifiers |= DM_NOTHROW; goto no_arg;
1732 case GNU_AK_TRANSPARENT_UNION: modifiers |= DM_TRANSPARENT_UNION; goto no_arg;
1733 case GNU_AK_CONSTRUCTOR: modifiers |= DM_CONSTRUCTOR; goto no_arg;
1734 case GNU_AK_DESTRUCTOR: modifiers |= DM_DESTRUCTOR; goto no_arg;
1735 case GNU_AK_DEPRECATED: modifiers |= DM_DEPRECATED; goto no_arg;
1737 case GNU_AK_ALIGNED:
1738 /* __align__ may be used without an argument */
1739 if (attribute->have_arguments) {
1740 parse_gnu_attribute_const_arg(attribute);
1744 case GNU_AK_FORMAT_ARG:
1745 case GNU_AK_REGPARM:
1746 case GNU_AK_TRAP_EXIT:
1747 if (!attribute->have_arguments) {
1748 /* should have arguments */
1749 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1750 attribute->invalid = true;
1752 parse_gnu_attribute_const_arg(attribute);
1755 case GNU_AK_SECTION:
1756 case GNU_AK_SP_SWITCH:
1757 if (!attribute->have_arguments) {
1758 /* should have arguments */
1759 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1760 attribute->invalid = true;
1762 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1765 if (!attribute->have_arguments) {
1766 /* should have arguments */
1767 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1768 attribute->invalid = true;
1770 parse_gnu_attribute_format_args(attribute);
1772 case GNU_AK_WEAKREF:
1773 /* may have one string argument */
1774 if (attribute->have_arguments)
1775 parse_gnu_attribute_string_arg(attribute, &attribute->u.string);
1777 case GNU_AK_NONNULL:
1778 if (attribute->have_arguments)
1779 parse_gnu_attribute_const_arg_list(attribute);
1781 case GNU_AK_TLS_MODEL:
1782 if (!attribute->have_arguments) {
1783 /* should have arguments */
1784 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1786 parse_gnu_attribute_tls_model_arg(attribute);
1788 case GNU_AK_VISIBILITY:
1789 if (!attribute->have_arguments) {
1790 /* should have arguments */
1791 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1793 parse_gnu_attribute_visibility_arg(attribute);
1796 if (!attribute->have_arguments) {
1797 /* should have arguments */
1798 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1800 parse_gnu_attribute_model_arg(attribute);
1804 if (!attribute->have_arguments) {
1805 /* should have arguments */
1806 errorf(HERE, "wrong number of arguments specified for '%s' attribute", name);
1808 parse_gnu_attribute_mode_arg(attribute);
1811 case GNU_AK_INTERRUPT:
1812 /* may have one string argument */
1813 if (attribute->have_arguments)
1814 parse_gnu_attribute_interrupt_arg(attribute);
1816 case GNU_AK_SENTINEL:
1817 /* may have one string argument */
1818 if (attribute->have_arguments)
1819 parse_gnu_attribute_const_arg(attribute);
1822 /* already handled */
1826 check_no_argument(attribute, name);
1829 if (attribute != NULL) {
1831 last->next = attribute;
1834 head = last = attribute;
1838 if (token.type != ',')
1852 * Parse GNU attributes.
1854 static decl_modifiers_t parse_attributes(gnu_attribute_t **attributes)
1856 decl_modifiers_t modifiers = 0;
1859 switch (token.type) {
1860 case T___attribute__:
1861 modifiers |= parse_gnu_attribute(attributes);
1867 if (token.type != T_STRING_LITERAL) {
1868 parse_error_expected("while parsing assembler attribute",
1869 T_STRING_LITERAL, NULL);
1870 eat_until_matching_token('(');
1873 parse_string_literals();
1878 case T_cdecl: modifiers |= DM_CDECL; break;
1879 case T__fastcall: modifiers |= DM_FASTCALL; break;
1880 case T__stdcall: modifiers |= DM_STDCALL; break;
1883 /* TODO record modifier */
1885 warningf(HERE, "Ignoring declaration modifier %K", &token);
1889 default: return modifiers;
1896 static void mark_vars_read(expression_t *expr, variable_t *lhs_var);
1898 static variable_t *determine_lhs_var(expression_t *const expr,
1899 variable_t *lhs_var)
1901 switch (expr->kind) {
1902 case EXPR_REFERENCE: {
1903 entity_t *const entity = expr->reference.entity;
1904 /* we should only find variables as lavlues... */
1905 if (entity->base.kind != ENTITY_VARIABLE)
1908 return &entity->variable;
1911 case EXPR_ARRAY_ACCESS: {
1912 expression_t *const ref = expr->array_access.array_ref;
1913 variable_t * var = NULL;
1914 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1915 var = determine_lhs_var(ref, lhs_var);
1918 mark_vars_read(expr->select.compound, lhs_var);
1920 mark_vars_read(expr->array_access.index, lhs_var);
1925 if (is_type_compound(skip_typeref(expr->base.type))) {
1926 return determine_lhs_var(expr->select.compound, lhs_var);
1928 mark_vars_read(expr->select.compound, lhs_var);
1933 case EXPR_UNARY_DEREFERENCE: {
1934 expression_t *const val = expr->unary.value;
1935 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1937 return determine_lhs_var(val->unary.value, lhs_var);
1939 mark_vars_read(val, NULL);
1945 mark_vars_read(expr, NULL);
1950 #define VAR_ANY ((variable_t*)-1)
1953 * Mark declarations, which are read. This is used to deted variables, which
1957 * x is not marked as "read", because it is only read to calculate its own new
1961 * x and y are not detected as "not read", because multiple variables are
1964 static void mark_vars_read(expression_t *const expr, variable_t *lhs_var)
1966 switch (expr->kind) {
1967 case EXPR_REFERENCE: {
1968 entity_t *const entity = expr->reference.entity;
1969 if (entity->kind != ENTITY_VARIABLE)
1972 variable_t *variable = &entity->variable;
1973 if (lhs_var != variable && lhs_var != VAR_ANY) {
1974 variable->read = true;
1980 // TODO respect pure/const
1981 mark_vars_read(expr->call.function, NULL);
1982 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1983 mark_vars_read(arg->expression, NULL);
1987 case EXPR_CONDITIONAL:
1988 // TODO lhs_decl should depend on whether true/false have an effect
1989 mark_vars_read(expr->conditional.condition, NULL);
1990 if (expr->conditional.true_expression != NULL)
1991 mark_vars_read(expr->conditional.true_expression, lhs_var);
1992 mark_vars_read(expr->conditional.false_expression, lhs_var);
1996 if (lhs_var == VAR_ANY && !is_type_compound(skip_typeref(expr->base.type)))
1998 mark_vars_read(expr->select.compound, lhs_var);
2001 case EXPR_ARRAY_ACCESS: {
2002 expression_t *const ref = expr->array_access.array_ref;
2003 mark_vars_read(ref, lhs_var);
2004 lhs_var = determine_lhs_var(ref, lhs_var);
2005 mark_vars_read(expr->array_access.index, lhs_var);
2010 mark_vars_read(expr->va_arge.ap, lhs_var);
2013 case EXPR_UNARY_CAST:
2014 /* Special case: Use void cast to mark a variable as "read" */
2015 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
2020 case EXPR_UNARY_THROW:
2021 if (expr->unary.value == NULL)
2024 case EXPR_UNARY_DEREFERENCE:
2025 case EXPR_UNARY_DELETE:
2026 case EXPR_UNARY_DELETE_ARRAY:
2027 if (lhs_var == VAR_ANY)
2031 case EXPR_UNARY_NEGATE:
2032 case EXPR_UNARY_PLUS:
2033 case EXPR_UNARY_BITWISE_NEGATE:
2034 case EXPR_UNARY_NOT:
2035 case EXPR_UNARY_TAKE_ADDRESS:
2036 case EXPR_UNARY_POSTFIX_INCREMENT:
2037 case EXPR_UNARY_POSTFIX_DECREMENT:
2038 case EXPR_UNARY_PREFIX_INCREMENT:
2039 case EXPR_UNARY_PREFIX_DECREMENT:
2040 case EXPR_UNARY_CAST_IMPLICIT:
2041 case EXPR_UNARY_ASSUME:
2043 mark_vars_read(expr->unary.value, lhs_var);
2046 case EXPR_BINARY_ADD:
2047 case EXPR_BINARY_SUB:
2048 case EXPR_BINARY_MUL:
2049 case EXPR_BINARY_DIV:
2050 case EXPR_BINARY_MOD:
2051 case EXPR_BINARY_EQUAL:
2052 case EXPR_BINARY_NOTEQUAL:
2053 case EXPR_BINARY_LESS:
2054 case EXPR_BINARY_LESSEQUAL:
2055 case EXPR_BINARY_GREATER:
2056 case EXPR_BINARY_GREATEREQUAL:
2057 case EXPR_BINARY_BITWISE_AND:
2058 case EXPR_BINARY_BITWISE_OR:
2059 case EXPR_BINARY_BITWISE_XOR:
2060 case EXPR_BINARY_LOGICAL_AND:
2061 case EXPR_BINARY_LOGICAL_OR:
2062 case EXPR_BINARY_SHIFTLEFT:
2063 case EXPR_BINARY_SHIFTRIGHT:
2064 case EXPR_BINARY_COMMA:
2065 case EXPR_BINARY_ISGREATER:
2066 case EXPR_BINARY_ISGREATEREQUAL:
2067 case EXPR_BINARY_ISLESS:
2068 case EXPR_BINARY_ISLESSEQUAL:
2069 case EXPR_BINARY_ISLESSGREATER:
2070 case EXPR_BINARY_ISUNORDERED:
2071 mark_vars_read(expr->binary.left, lhs_var);
2072 mark_vars_read(expr->binary.right, lhs_var);
2075 case EXPR_BINARY_ASSIGN:
2076 case EXPR_BINARY_MUL_ASSIGN:
2077 case EXPR_BINARY_DIV_ASSIGN:
2078 case EXPR_BINARY_MOD_ASSIGN:
2079 case EXPR_BINARY_ADD_ASSIGN:
2080 case EXPR_BINARY_SUB_ASSIGN:
2081 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
2082 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
2083 case EXPR_BINARY_BITWISE_AND_ASSIGN:
2084 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
2085 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
2086 if (lhs_var == VAR_ANY)
2088 lhs_var = determine_lhs_var(expr->binary.left, lhs_var);
2089 mark_vars_read(expr->binary.right, lhs_var);
2094 determine_lhs_var(expr->va_starte.ap, lhs_var);
2100 case EXPR_CHARACTER_CONSTANT:
2101 case EXPR_WIDE_CHARACTER_CONSTANT:
2102 case EXPR_STRING_LITERAL:
2103 case EXPR_WIDE_STRING_LITERAL:
2104 case EXPR_COMPOUND_LITERAL: // TODO init?
2106 case EXPR_CLASSIFY_TYPE:
2109 case EXPR_BUILTIN_SYMBOL:
2110 case EXPR_BUILTIN_CONSTANT_P:
2111 case EXPR_BUILTIN_PREFETCH:
2113 case EXPR_STATEMENT: // TODO
2114 case EXPR_LABEL_ADDRESS:
2115 case EXPR_BINARY_BUILTIN_EXPECT:
2116 case EXPR_REFERENCE_ENUM_VALUE:
2120 panic("unhandled expression");
2123 static designator_t *parse_designation(void)
2125 designator_t *result = NULL;
2126 designator_t *last = NULL;
2129 designator_t *designator;
2130 switch (token.type) {
2132 designator = allocate_ast_zero(sizeof(designator[0]));
2133 designator->source_position = token.source_position;
2135 add_anchor_token(']');
2136 designator->array_index = parse_constant_expression();
2137 rem_anchor_token(']');
2141 designator = allocate_ast_zero(sizeof(designator[0]));
2142 designator->source_position = token.source_position;
2144 if (token.type != T_IDENTIFIER) {
2145 parse_error_expected("while parsing designator",
2146 T_IDENTIFIER, NULL);
2149 designator->symbol = token.v.symbol;
2157 assert(designator != NULL);
2159 last->next = designator;
2161 result = designator;
2169 static initializer_t *initializer_from_string(array_type_t *type,
2170 const string_t *const string)
2172 /* TODO: check len vs. size of array type */
2175 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
2176 initializer->string.string = *string;
2181 static initializer_t *initializer_from_wide_string(array_type_t *const type,
2182 wide_string_t *const string)
2184 /* TODO: check len vs. size of array type */
2187 initializer_t *const initializer =
2188 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
2189 initializer->wide_string.string = *string;
2195 * Build an initializer from a given expression.
2197 static initializer_t *initializer_from_expression(type_t *orig_type,
2198 expression_t *expression)
2200 /* TODO check that expression is a constant expression */
2202 /* § 6.7.8.14/15 char array may be initialized by string literals */
2203 type_t *type = skip_typeref(orig_type);
2204 type_t *expr_type_orig = expression->base.type;
2205 type_t *expr_type = skip_typeref(expr_type_orig);
2206 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
2207 array_type_t *const array_type = &type->array;
2208 type_t *const element_type = skip_typeref(array_type->element_type);
2210 if (element_type->kind == TYPE_ATOMIC) {
2211 atomic_type_kind_t akind = element_type->atomic.akind;
2212 switch (expression->kind) {
2213 case EXPR_STRING_LITERAL:
2214 if (akind == ATOMIC_TYPE_CHAR
2215 || akind == ATOMIC_TYPE_SCHAR
2216 || akind == ATOMIC_TYPE_UCHAR) {
2217 return initializer_from_string(array_type,
2218 &expression->string.value);
2221 case EXPR_WIDE_STRING_LITERAL: {
2222 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
2223 if (get_unqualified_type(element_type) == bare_wchar_type) {
2224 return initializer_from_wide_string(array_type,
2225 &expression->wide_string.value);
2235 assign_error_t error = semantic_assign(type, expression);
2236 if (error == ASSIGN_ERROR_INCOMPATIBLE)
2238 report_assign_error(error, type, expression, "initializer",
2239 &expression->base.source_position);
2241 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
2243 if (type->kind == TYPE_BITFIELD) {
2244 type = type->bitfield.base_type;
2247 result->value.value = create_implicit_cast(expression, type);
2253 * Checks if a given expression can be used as an constant initializer.
2255 static bool is_initializer_constant(const expression_t *expression)
2257 return is_constant_expression(expression)
2258 || is_address_constant(expression);
2262 * Parses an scalar initializer.
2264 * § 6.7.8.11; eat {} without warning
2266 static initializer_t *parse_scalar_initializer(type_t *type,
2267 bool must_be_constant)
2269 /* there might be extra {} hierarchies */
2271 if (token.type == '{') {
2273 warningf(HERE, "extra curly braces around scalar initializer");
2277 } while (token.type == '{');
2280 expression_t *expression = parse_assignment_expression();
2281 mark_vars_read(expression, NULL);
2282 if (must_be_constant && !is_initializer_constant(expression)) {
2283 errorf(&expression->base.source_position,
2284 "Initialisation expression '%E' is not constant\n",
2288 initializer_t *initializer = initializer_from_expression(type, expression);
2290 if (initializer == NULL) {
2291 errorf(&expression->base.source_position,
2292 "expression '%E' (type '%T') doesn't match expected type '%T'",
2293 expression, expression->base.type, type);
2298 bool additional_warning_displayed = false;
2299 while (braces > 0) {
2300 if (token.type == ',') {
2303 if (token.type != '}') {
2304 if (!additional_warning_displayed && warning.other) {
2305 warningf(HERE, "additional elements in scalar initializer");
2306 additional_warning_displayed = true;
2317 * An entry in the type path.
2319 typedef struct type_path_entry_t type_path_entry_t;
2320 struct type_path_entry_t {
2321 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
2323 size_t index; /**< For array types: the current index. */
2324 declaration_t *compound_entry; /**< For compound types: the current declaration. */
2329 * A type path expression a position inside compound or array types.
2331 typedef struct type_path_t type_path_t;
2332 struct type_path_t {
2333 type_path_entry_t *path; /**< An flexible array containing the current path. */
2334 type_t *top_type; /**< type of the element the path points */
2335 size_t max_index; /**< largest index in outermost array */
2339 * Prints a type path for debugging.
2341 static __attribute__((unused)) void debug_print_type_path(
2342 const type_path_t *path)
2344 size_t len = ARR_LEN(path->path);
2346 for(size_t i = 0; i < len; ++i) {
2347 const type_path_entry_t *entry = & path->path[i];
2349 type_t *type = skip_typeref(entry->type);
2350 if (is_type_compound(type)) {
2351 /* in gcc mode structs can have no members */
2352 if (entry->v.compound_entry == NULL) {
2356 fprintf(stderr, ".%s",
2357 entry->v.compound_entry->base.symbol->string);
2358 } else if (is_type_array(type)) {
2359 fprintf(stderr, "[%zu]", entry->v.index);
2361 fprintf(stderr, "-INVALID-");
2364 if (path->top_type != NULL) {
2365 fprintf(stderr, " (");
2366 print_type(path->top_type);
2367 fprintf(stderr, ")");
2372 * Return the top type path entry, ie. in a path
2373 * (type).a.b returns the b.
2375 static type_path_entry_t *get_type_path_top(const type_path_t *path)
2377 size_t len = ARR_LEN(path->path);
2379 return &path->path[len-1];
2383 * Enlarge the type path by an (empty) element.
2385 static type_path_entry_t *append_to_type_path(type_path_t *path)
2387 size_t len = ARR_LEN(path->path);
2388 ARR_RESIZE(type_path_entry_t, path->path, len+1);
2390 type_path_entry_t *result = & path->path[len];
2391 memset(result, 0, sizeof(result[0]));
2396 * Descending into a sub-type. Enter the scope of the current top_type.
2398 static void descend_into_subtype(type_path_t *path)
2400 type_t *orig_top_type = path->top_type;
2401 type_t *top_type = skip_typeref(orig_top_type);
2403 type_path_entry_t *top = append_to_type_path(path);
2404 top->type = top_type;
2406 if (is_type_compound(top_type)) {
2407 compound_t *compound = top_type->compound.compound;
2408 entity_t *entry = compound->members.entities;
2410 if (entry != NULL) {
2411 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2412 top->v.compound_entry = &entry->declaration;
2413 path->top_type = entry->declaration.type;
2415 path->top_type = NULL;
2417 } else if (is_type_array(top_type)) {
2419 path->top_type = top_type->array.element_type;
2421 assert(!is_type_valid(top_type));
2426 * Pop an entry from the given type path, ie. returning from
2427 * (type).a.b to (type).a
2429 static void ascend_from_subtype(type_path_t *path)
2431 type_path_entry_t *top = get_type_path_top(path);
2433 path->top_type = top->type;
2435 size_t len = ARR_LEN(path->path);
2436 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2440 * Pop entries from the given type path until the given
2441 * path level is reached.
2443 static void ascend_to(type_path_t *path, size_t top_path_level)
2445 size_t len = ARR_LEN(path->path);
2447 while (len > top_path_level) {
2448 ascend_from_subtype(path);
2449 len = ARR_LEN(path->path);
2453 static bool walk_designator(type_path_t *path, const designator_t *designator,
2454 bool used_in_offsetof)
2456 for( ; designator != NULL; designator = designator->next) {
2457 type_path_entry_t *top = get_type_path_top(path);
2458 type_t *orig_type = top->type;
2460 type_t *type = skip_typeref(orig_type);
2462 if (designator->symbol != NULL) {
2463 symbol_t *symbol = designator->symbol;
2464 if (!is_type_compound(type)) {
2465 if (is_type_valid(type)) {
2466 errorf(&designator->source_position,
2467 "'.%Y' designator used for non-compound type '%T'",
2471 top->type = type_error_type;
2472 top->v.compound_entry = NULL;
2473 orig_type = type_error_type;
2475 compound_t *compound = type->compound.compound;
2476 entity_t *iter = compound->members.entities;
2477 for( ; iter != NULL; iter = iter->base.next) {
2478 if (iter->base.symbol == symbol) {
2483 errorf(&designator->source_position,
2484 "'%T' has no member named '%Y'", orig_type, symbol);
2487 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2488 if (used_in_offsetof) {
2489 type_t *real_type = skip_typeref(iter->declaration.type);
2490 if (real_type->kind == TYPE_BITFIELD) {
2491 errorf(&designator->source_position,
2492 "offsetof designator '%Y' may not specify bitfield",
2498 top->type = orig_type;
2499 top->v.compound_entry = &iter->declaration;
2500 orig_type = iter->declaration.type;
2503 expression_t *array_index = designator->array_index;
2504 assert(designator->array_index != NULL);
2506 if (!is_type_array(type)) {
2507 if (is_type_valid(type)) {
2508 errorf(&designator->source_position,
2509 "[%E] designator used for non-array type '%T'",
2510 array_index, orig_type);
2515 long index = fold_constant(array_index);
2516 if (!used_in_offsetof) {
2518 errorf(&designator->source_position,
2519 "array index [%E] must be positive", array_index);
2520 } else if (type->array.size_constant) {
2521 long array_size = type->array.size;
2522 if (index >= array_size) {
2523 errorf(&designator->source_position,
2524 "designator [%E] (%d) exceeds array size %d",
2525 array_index, index, array_size);
2530 top->type = orig_type;
2531 top->v.index = (size_t) index;
2532 orig_type = type->array.element_type;
2534 path->top_type = orig_type;
2536 if (designator->next != NULL) {
2537 descend_into_subtype(path);
2546 static void advance_current_object(type_path_t *path, size_t top_path_level)
2548 type_path_entry_t *top = get_type_path_top(path);
2550 type_t *type = skip_typeref(top->type);
2551 if (is_type_union(type)) {
2552 /* in unions only the first element is initialized */
2553 top->v.compound_entry = NULL;
2554 } else if (is_type_struct(type)) {
2555 declaration_t *entry = top->v.compound_entry;
2557 entity_t *next_entity = entry->base.next;
2558 if (next_entity != NULL) {
2559 assert(is_declaration(next_entity));
2560 entry = &next_entity->declaration;
2565 top->v.compound_entry = entry;
2566 if (entry != NULL) {
2567 path->top_type = entry->type;
2570 } else if (is_type_array(type)) {
2571 assert(is_type_array(type));
2575 if (!type->array.size_constant || top->v.index < type->array.size) {
2579 assert(!is_type_valid(type));
2583 /* we're past the last member of the current sub-aggregate, try if we
2584 * can ascend in the type hierarchy and continue with another subobject */
2585 size_t len = ARR_LEN(path->path);
2587 if (len > top_path_level) {
2588 ascend_from_subtype(path);
2589 advance_current_object(path, top_path_level);
2591 path->top_type = NULL;
2596 * skip until token is found.
2598 static void skip_until(int type)
2600 while (token.type != type) {
2601 if (token.type == T_EOF)
2608 * skip any {...} blocks until a closing bracket is reached.
2610 static void skip_initializers(void)
2612 if (token.type == '{')
2615 while (token.type != '}') {
2616 if (token.type == T_EOF)
2618 if (token.type == '{') {
2626 static initializer_t *create_empty_initializer(void)
2628 static initializer_t empty_initializer
2629 = { .list = { { INITIALIZER_LIST }, 0 } };
2630 return &empty_initializer;
2634 * Parse a part of an initialiser for a struct or union,
2636 static initializer_t *parse_sub_initializer(type_path_t *path,
2637 type_t *outer_type, size_t top_path_level,
2638 parse_initializer_env_t *env)
2640 if (token.type == '}') {
2641 /* empty initializer */
2642 return create_empty_initializer();
2645 type_t *orig_type = path->top_type;
2646 type_t *type = NULL;
2648 if (orig_type == NULL) {
2649 /* We are initializing an empty compound. */
2651 type = skip_typeref(orig_type);
2654 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2657 designator_t *designator = NULL;
2658 if (token.type == '.' || token.type == '[') {
2659 designator = parse_designation();
2660 goto finish_designator;
2661 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2662 /* GNU-style designator ("identifier: value") */
2663 designator = allocate_ast_zero(sizeof(designator[0]));
2664 designator->source_position = token.source_position;
2665 designator->symbol = token.v.symbol;
2670 /* reset path to toplevel, evaluate designator from there */
2671 ascend_to(path, top_path_level);
2672 if (!walk_designator(path, designator, false)) {
2673 /* can't continue after designation error */
2677 initializer_t *designator_initializer
2678 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2679 designator_initializer->designator.designator = designator;
2680 ARR_APP1(initializer_t*, initializers, designator_initializer);
2682 orig_type = path->top_type;
2683 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2688 if (token.type == '{') {
2689 if (type != NULL && is_type_scalar(type)) {
2690 sub = parse_scalar_initializer(type, env->must_be_constant);
2694 if (env->entity != NULL) {
2696 "extra brace group at end of initializer for '%Y'",
2697 env->entity->base.symbol);
2699 errorf(HERE, "extra brace group at end of initializer");
2702 descend_into_subtype(path);
2704 add_anchor_token('}');
2705 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2707 rem_anchor_token('}');
2710 ascend_from_subtype(path);
2714 goto error_parse_next;
2718 /* must be an expression */
2719 expression_t *expression = parse_assignment_expression();
2721 if (env->must_be_constant && !is_initializer_constant(expression)) {
2722 errorf(&expression->base.source_position,
2723 "Initialisation expression '%E' is not constant\n",
2728 /* we are already outside, ... */
2729 type_t *const outer_type_skip = skip_typeref(outer_type);
2730 if (is_type_compound(outer_type_skip) &&
2731 !outer_type_skip->compound.compound->complete) {
2732 goto error_parse_next;
2737 /* handle { "string" } special case */
2738 if ((expression->kind == EXPR_STRING_LITERAL
2739 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2740 && outer_type != NULL) {
2741 sub = initializer_from_expression(outer_type, expression);
2743 if (token.type == ',') {
2746 if (token.type != '}' && warning.other) {
2747 warningf(HERE, "excessive elements in initializer for type '%T'",
2750 /* TODO: eat , ... */
2755 /* descend into subtypes until expression matches type */
2757 orig_type = path->top_type;
2758 type = skip_typeref(orig_type);
2760 sub = initializer_from_expression(orig_type, expression);
2764 if (!is_type_valid(type)) {
2767 if (is_type_scalar(type)) {
2768 errorf(&expression->base.source_position,
2769 "expression '%E' doesn't match expected type '%T'",
2770 expression, orig_type);
2774 descend_into_subtype(path);
2778 /* update largest index of top array */
2779 const type_path_entry_t *first = &path->path[0];
2780 type_t *first_type = first->type;
2781 first_type = skip_typeref(first_type);
2782 if (is_type_array(first_type)) {
2783 size_t index = first->v.index;
2784 if (index > path->max_index)
2785 path->max_index = index;
2789 /* append to initializers list */
2790 ARR_APP1(initializer_t*, initializers, sub);
2793 if (warning.other) {
2794 if (env->entity != NULL) {
2795 warningf(HERE, "excess elements in struct initializer for '%Y'",
2796 env->entity->base.symbol);
2798 warningf(HERE, "excess elements in struct initializer");
2804 if (token.type == '}') {
2808 if (token.type == '}') {
2813 /* advance to the next declaration if we are not at the end */
2814 advance_current_object(path, top_path_level);
2815 orig_type = path->top_type;
2816 if (orig_type != NULL)
2817 type = skip_typeref(orig_type);
2823 size_t len = ARR_LEN(initializers);
2824 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2825 initializer_t *result = allocate_ast_zero(size);
2826 result->kind = INITIALIZER_LIST;
2827 result->list.len = len;
2828 memcpy(&result->list.initializers, initializers,
2829 len * sizeof(initializers[0]));
2831 DEL_ARR_F(initializers);
2832 ascend_to(path, top_path_level+1);
2837 skip_initializers();
2838 DEL_ARR_F(initializers);
2839 ascend_to(path, top_path_level+1);
2844 * Parses an initializer. Parsers either a compound literal
2845 * (env->declaration == NULL) or an initializer of a declaration.
2847 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2849 type_t *type = skip_typeref(env->type);
2850 initializer_t *result = NULL;
2853 if (is_type_scalar(type)) {
2854 result = parse_scalar_initializer(type, env->must_be_constant);
2855 } else if (token.type == '{') {
2859 memset(&path, 0, sizeof(path));
2860 path.top_type = env->type;
2861 path.path = NEW_ARR_F(type_path_entry_t, 0);
2863 descend_into_subtype(&path);
2865 add_anchor_token('}');
2866 result = parse_sub_initializer(&path, env->type, 1, env);
2867 rem_anchor_token('}');
2869 max_index = path.max_index;
2870 DEL_ARR_F(path.path);
2874 /* parse_scalar_initializer() also works in this case: we simply
2875 * have an expression without {} around it */
2876 result = parse_scalar_initializer(type, env->must_be_constant);
2879 /* § 6.7.8 (22) array initializers for arrays with unknown size determine
2880 * the array type size */
2881 if (is_type_array(type) && type->array.size_expression == NULL
2882 && result != NULL) {
2884 switch (result->kind) {
2885 case INITIALIZER_LIST:
2886 size = max_index + 1;
2889 case INITIALIZER_STRING:
2890 size = result->string.string.size;
2893 case INITIALIZER_WIDE_STRING:
2894 size = result->wide_string.string.size;
2897 case INITIALIZER_DESIGNATOR:
2898 case INITIALIZER_VALUE:
2899 /* can happen for parse errors */
2904 internal_errorf(HERE, "invalid initializer type");
2907 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2908 cnst->base.type = type_size_t;
2909 cnst->conste.v.int_value = size;
2911 type_t *new_type = duplicate_type(type);
2913 new_type->array.size_expression = cnst;
2914 new_type->array.size_constant = true;
2915 new_type->array.has_implicit_size = true;
2916 new_type->array.size = size;
2917 env->type = new_type;
2925 static void append_entity(scope_t *scope, entity_t *entity)
2927 if (scope->last_entity != NULL) {
2928 scope->last_entity->base.next = entity;
2930 scope->entities = entity;
2932 scope->last_entity = entity;
2936 static compound_t *parse_compound_type_specifier(bool is_struct)
2938 gnu_attribute_t *attributes = NULL;
2939 decl_modifiers_t modifiers = 0;
2946 symbol_t *symbol = NULL;
2947 compound_t *compound = NULL;
2949 if (token.type == T___attribute__) {
2950 modifiers |= parse_attributes(&attributes);
2953 if (token.type == T_IDENTIFIER) {
2954 symbol = token.v.symbol;
2957 namespace_t const namespc =
2958 is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION;
2959 entity_t *entity = get_entity(symbol, namespc);
2960 if (entity != NULL) {
2961 assert(entity->kind == (is_struct ? ENTITY_STRUCT : ENTITY_UNION));
2962 compound = &entity->compound;
2963 if (compound->base.parent_scope != scope &&
2964 (token.type == '{' || token.type == ';')) {
2965 /* we're in an inner scope and have a definition. Override
2966 existing definition in outer scope */
2968 } else if (compound->complete && token.type == '{') {
2969 assert(symbol != NULL);
2970 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2971 is_struct ? "struct" : "union", symbol,
2972 &compound->base.source_position);
2973 /* clear members in the hope to avoid further errors */
2974 compound->members.entities = NULL;
2977 } else if (token.type != '{') {
2979 parse_error_expected("while parsing struct type specifier",
2980 T_IDENTIFIER, '{', NULL);
2982 parse_error_expected("while parsing union type specifier",
2983 T_IDENTIFIER, '{', NULL);
2989 if (compound == NULL) {
2990 entity_kind_t kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2991 entity_t *entity = allocate_entity_zero(kind);
2992 compound = &entity->compound;
2994 compound->base.namespc =
2995 (is_struct ? NAMESPACE_STRUCT : NAMESPACE_UNION);
2996 compound->base.source_position = token.source_position;
2997 compound->base.symbol = symbol;
2998 compound->base.parent_scope = scope;
2999 if (symbol != NULL) {
3000 environment_push(entity);
3002 append_entity(scope, entity);
3005 if (token.type == '{') {
3006 compound->complete = true;
3008 parse_compound_type_entries(compound);
3009 modifiers |= parse_attributes(&attributes);
3012 compound->modifiers |= modifiers;
3016 static void parse_enum_entries(type_t *const enum_type)
3020 if (token.type == '}') {
3022 errorf(HERE, "empty enum not allowed");
3026 add_anchor_token('}');
3028 if (token.type != T_IDENTIFIER) {
3029 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
3031 rem_anchor_token('}');
3035 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
3036 entity->enum_value.enum_type = enum_type;
3037 entity->base.symbol = token.v.symbol;
3038 entity->base.source_position = token.source_position;
3041 if (token.type == '=') {
3043 expression_t *value = parse_constant_expression();
3045 value = create_implicit_cast(value, enum_type);
3046 entity->enum_value.value = value;
3051 record_entity(entity, false);
3053 if (token.type != ',')
3056 } while (token.type != '}');
3057 rem_anchor_token('}');
3065 static type_t *parse_enum_specifier(void)
3067 gnu_attribute_t *attributes = NULL;
3072 if (token.type == T_IDENTIFIER) {
3073 symbol = token.v.symbol;
3076 entity = get_entity(symbol, NAMESPACE_ENUM);
3077 assert(entity == NULL || entity->kind == ENTITY_ENUM);
3078 } else if (token.type != '{') {
3079 parse_error_expected("while parsing enum type specifier",
3080 T_IDENTIFIER, '{', NULL);
3087 if (entity == NULL) {
3088 entity = allocate_entity_zero(ENTITY_ENUM);
3089 entity->base.namespc = NAMESPACE_ENUM;
3090 entity->base.source_position = token.source_position;
3091 entity->base.symbol = symbol;
3092 entity->base.parent_scope = scope;
3095 type_t *const type = allocate_type_zero(TYPE_ENUM);
3096 type->enumt.enume = &entity->enume;
3098 if (token.type == '{') {
3099 if (entity->enume.complete) {
3100 errorf(HERE, "multiple definitions of enum %Y (previous definition %P)",
3101 symbol, &entity->base.source_position);
3103 if (symbol != NULL) {
3104 environment_push(entity);
3106 append_entity(scope, entity);
3107 entity->enume.complete = true;
3109 parse_enum_entries(type);
3110 parse_attributes(&attributes);
3111 } else if(!entity->enume.complete && !(c_mode & _GNUC)) {
3112 errorf(HERE, "enum %Y used before definition (incomplete enumes are a GNU extension)",
3120 * if a symbol is a typedef to another type, return true
3122 static bool is_typedef_symbol(symbol_t *symbol)
3124 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
3125 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
3128 static type_t *parse_typeof(void)
3135 add_anchor_token(')');
3137 expression_t *expression = NULL;
3139 bool old_type_prop = in_type_prop;
3140 bool old_gcc_extension = in_gcc_extension;
3141 in_type_prop = true;
3143 while (token.type == T___extension__) {
3144 /* This can be a prefix to a typename or an expression. */
3146 in_gcc_extension = true;
3148 switch (token.type) {
3150 if (is_typedef_symbol(token.v.symbol)) {
3151 type = parse_typename();
3153 expression = parse_expression();
3154 type = expression->base.type;
3159 type = parse_typename();
3163 expression = parse_expression();
3164 type = expression->base.type;
3167 in_type_prop = old_type_prop;
3168 in_gcc_extension = old_gcc_extension;
3170 rem_anchor_token(')');
3173 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
3174 typeof_type->typeoft.expression = expression;
3175 typeof_type->typeoft.typeof_type = type;
3182 typedef enum specifiers_t {
3183 SPECIFIER_SIGNED = 1 << 0,
3184 SPECIFIER_UNSIGNED = 1 << 1,
3185 SPECIFIER_LONG = 1 << 2,
3186 SPECIFIER_INT = 1 << 3,
3187 SPECIFIER_DOUBLE = 1 << 4,
3188 SPECIFIER_CHAR = 1 << 5,
3189 SPECIFIER_SHORT = 1 << 6,
3190 SPECIFIER_LONG_LONG = 1 << 7,
3191 SPECIFIER_FLOAT = 1 << 8,
3192 SPECIFIER_BOOL = 1 << 9,
3193 SPECIFIER_VOID = 1 << 10,
3194 SPECIFIER_INT8 = 1 << 11,
3195 SPECIFIER_INT16 = 1 << 12,
3196 SPECIFIER_INT32 = 1 << 13,
3197 SPECIFIER_INT64 = 1 << 14,
3198 SPECIFIER_INT128 = 1 << 15,
3199 SPECIFIER_COMPLEX = 1 << 16,
3200 SPECIFIER_IMAGINARY = 1 << 17,
3203 static type_t *create_builtin_type(symbol_t *const symbol,
3204 type_t *const real_type)
3206 type_t *type = allocate_type_zero(TYPE_BUILTIN);
3207 type->builtin.symbol = symbol;
3208 type->builtin.real_type = real_type;
3210 type_t *result = typehash_insert(type);
3211 if (type != result) {
3218 static type_t *get_typedef_type(symbol_t *symbol)
3220 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
3221 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
3224 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
3225 type->typedeft.typedefe = &entity->typedefe;
3231 * check for the allowed MS alignment values.
3233 static bool check_alignment_value(long long intvalue)
3235 if (intvalue < 1 || intvalue > 8192) {
3236 errorf(HERE, "illegal alignment value");
3239 unsigned v = (unsigned)intvalue;
3240 for (unsigned i = 1; i <= 8192; i += i) {
3244 errorf(HERE, "alignment must be power of two");
3248 #define DET_MOD(name, tag) do { \
3249 if (*modifiers & tag && warning.other) warningf(HERE, #name " used more than once"); \
3250 *modifiers |= tag; \
3253 static void parse_microsoft_extended_decl_modifier(declaration_specifiers_t *specifiers)
3255 decl_modifiers_t *modifiers = &specifiers->modifiers;
3258 if (token.type == T_restrict) {
3260 DET_MOD(restrict, DM_RESTRICT);
3262 } else if (token.type != T_IDENTIFIER)
3264 symbol_t *symbol = token.v.symbol;
3265 if (symbol == sym_align) {
3268 if (token.type != T_INTEGER)
3270 if (check_alignment_value(token.v.intvalue)) {
3271 if (specifiers->alignment != 0 && warning.other)
3272 warningf(HERE, "align used more than once");
3273 specifiers->alignment = (unsigned char)token.v.intvalue;
3277 } else if (symbol == sym_allocate) {
3280 if (token.type != T_IDENTIFIER)
3282 (void)token.v.symbol;
3284 } else if (symbol == sym_dllimport) {
3286 DET_MOD(dllimport, DM_DLLIMPORT);
3287 } else if (symbol == sym_dllexport) {
3289 DET_MOD(dllexport, DM_DLLEXPORT);
3290 } else if (symbol == sym_thread) {
3292 DET_MOD(thread, DM_THREAD);
3293 } else if (symbol == sym_naked) {
3295 DET_MOD(naked, DM_NAKED);
3296 } else if (symbol == sym_noinline) {
3298 DET_MOD(noinline, DM_NOINLINE);
3299 } else if (symbol == sym_noreturn) {
3301 DET_MOD(noreturn, DM_NORETURN);
3302 } else if (symbol == sym_nothrow) {
3304 DET_MOD(nothrow, DM_NOTHROW);
3305 } else if (symbol == sym_novtable) {
3307 DET_MOD(novtable, DM_NOVTABLE);
3308 } else if (symbol == sym_property) {
3312 bool is_get = false;
3313 if (token.type != T_IDENTIFIER)
3315 if (token.v.symbol == sym_get) {
3317 } else if (token.v.symbol == sym_put) {
3319 errorf(HERE, "Bad property name '%Y'", token.v.symbol);
3324 if (token.type != T_IDENTIFIER)
3327 if (specifiers->get_property_sym != NULL) {
3328 errorf(HERE, "get property name already specified");
3330 specifiers->get_property_sym = token.v.symbol;
3333 if (specifiers->put_property_sym != NULL) {
3334 errorf(HERE, "put property name already specified");
3336 specifiers->put_property_sym = token.v.symbol;
3340 if (token.type == ',') {
3347 } else if (symbol == sym_selectany) {
3349 DET_MOD(selectany, DM_SELECTANY);
3350 } else if (symbol == sym_uuid) {
3353 if (token.type != T_STRING_LITERAL)
3357 } else if (symbol == sym_deprecated) {
3359 if (specifiers->deprecated != 0 && warning.other)
3360 warningf(HERE, "deprecated used more than once");
3361 specifiers->deprecated = true;
3362 if (token.type == '(') {
3364 if (token.type == T_STRING_LITERAL) {
3365 specifiers->deprecated_string = token.v.string.begin;
3368 errorf(HERE, "string literal expected");
3372 } else if (symbol == sym_noalias) {
3374 DET_MOD(noalias, DM_NOALIAS);
3377 warningf(HERE, "Unknown modifier %Y ignored", token.v.symbol);
3379 if (token.type == '(')
3383 if (token.type == ',')
3390 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
3392 entity_t *entity = allocate_entity_zero(kind);
3393 entity->base.source_position = *HERE;
3394 entity->base.symbol = symbol;
3395 if (is_declaration(entity)) {
3396 entity->declaration.type = type_error_type;
3397 entity->declaration.implicit = true;
3398 } else if (kind == ENTITY_TYPEDEF) {
3399 entity->typedefe.type = type_error_type;
3401 record_entity(entity, false);
3406 * Finish the construction of a struct type by calculating
3407 * its size, offsets, alignment.
3409 static void finish_struct_type(compound_type_t *type)
3411 assert(type->compound != NULL);
3413 compound_t *compound = type->compound;
3414 if (!compound->complete)
3419 il_alignment_t alignment = 1;
3420 bool need_pad = false;
3422 entity_t *entry = compound->members.entities;
3423 for (; entry != NULL; entry = entry->base.next) {
3424 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3427 type_t *m_type = skip_typeref(entry->declaration.type);
3428 if (! is_type_valid(m_type)) {
3429 /* simply ignore errors here */
3432 il_alignment_t m_alignment = m_type->base.alignment;
3433 if (m_alignment > alignment)
3434 alignment = m_alignment;
3436 offset = (size + m_alignment - 1) & -m_alignment;
3440 entry->compound_member.offset = offset;
3441 size = offset + m_type->base.size;
3443 if (type->base.alignment != 0) {
3444 alignment = type->base.alignment;
3447 offset = (size + alignment - 1) & -alignment;
3451 if (warning.padded && need_pad) {
3452 warningf(&compound->base.source_position,
3453 "'%#T' needs padding", type, compound->base.symbol);
3455 if (warning.packed && !need_pad) {
3456 warningf(&compound->base.source_position,
3457 "superfluous packed attribute on '%#T'",
3458 type, compound->base.symbol);
3461 type->base.size = offset;
3462 type->base.alignment = alignment;
3466 * Finish the construction of an union type by calculating
3467 * its size and alignment.
3469 static void finish_union_type(compound_type_t *type)
3471 assert(type->compound != NULL);
3473 compound_t *compound = type->compound;
3474 if (! compound->complete)
3478 il_alignment_t alignment = 1;
3480 entity_t *entry = compound->members.entities;
3481 for (; entry != NULL; entry = entry->base.next) {
3482 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3485 type_t *m_type = skip_typeref(entry->declaration.type);
3486 if (! is_type_valid(m_type))
3489 entry->compound_member.offset = 0;
3490 if (m_type->base.size > size)
3491 size = m_type->base.size;
3492 if (m_type->base.alignment > alignment)
3493 alignment = m_type->base.alignment;
3495 if (type->base.alignment != 0) {
3496 alignment = type->base.alignment;
3498 size = (size + alignment - 1) & -alignment;
3499 type->base.size = size;
3500 type->base.alignment = alignment;
3503 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3505 type_t *type = NULL;
3506 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3507 type_modifiers_t modifiers = TYPE_MODIFIER_NONE;
3508 unsigned type_specifiers = 0;
3509 bool newtype = false;
3510 bool saw_error = false;
3511 bool old_gcc_extension = in_gcc_extension;
3513 specifiers->source_position = token.source_position;
3516 specifiers->modifiers
3517 |= parse_attributes(&specifiers->gnu_attributes);
3518 if (specifiers->modifiers & DM_TRANSPARENT_UNION)
3519 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3521 switch (token.type) {
3524 #define MATCH_STORAGE_CLASS(token, class) \
3526 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3527 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3529 specifiers->storage_class = class; \
3533 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3534 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3535 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3536 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3537 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3542 add_anchor_token(')');
3543 parse_microsoft_extended_decl_modifier(specifiers);
3544 rem_anchor_token(')');
3549 switch (specifiers->storage_class) {
3550 case STORAGE_CLASS_NONE:
3551 specifiers->storage_class = STORAGE_CLASS_THREAD;
3554 case STORAGE_CLASS_EXTERN:
3555 specifiers->storage_class = STORAGE_CLASS_THREAD_EXTERN;
3558 case STORAGE_CLASS_STATIC:
3559 specifiers->storage_class = STORAGE_CLASS_THREAD_STATIC;
3563 errorf(HERE, "multiple storage classes in declaration specifiers");
3569 /* type qualifiers */
3570 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3572 qualifiers |= qualifier; \
3576 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3577 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3578 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3579 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3580 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3581 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3582 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3583 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3585 case T___extension__:
3587 in_gcc_extension = true;
3590 /* type specifiers */
3591 #define MATCH_SPECIFIER(token, specifier, name) \
3594 if (type_specifiers & specifier) { \
3595 errorf(HERE, "multiple " name " type specifiers given"); \
3597 type_specifiers |= specifier; \
3601 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3602 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3603 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3604 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3605 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3606 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3607 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3608 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3609 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3610 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3611 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3612 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3613 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3614 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3615 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3616 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3617 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3619 case T__forceinline:
3620 /* only in microsoft mode */
3621 specifiers->modifiers |= DM_FORCEINLINE;
3626 specifiers->is_inline = true;
3631 if (type_specifiers & SPECIFIER_LONG_LONG) {
3632 errorf(HERE, "multiple type specifiers given");
3633 } else if (type_specifiers & SPECIFIER_LONG) {
3634 type_specifiers |= SPECIFIER_LONG_LONG;
3636 type_specifiers |= SPECIFIER_LONG;
3641 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3643 type->compound.compound = parse_compound_type_specifier(true);
3644 finish_struct_type(&type->compound);
3648 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3649 type->compound.compound = parse_compound_type_specifier(false);
3650 if (type->compound.compound->modifiers & DM_TRANSPARENT_UNION)
3651 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
3652 finish_union_type(&type->compound);
3656 type = parse_enum_specifier();
3659 type = parse_typeof();
3661 case T___builtin_va_list:
3662 type = duplicate_type(type_valist);
3666 case T_IDENTIFIER: {
3667 /* only parse identifier if we haven't found a type yet */
3668 if (type != NULL || type_specifiers != 0) {
3669 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3670 * declaration, so it doesn't generate errors about expecting '(' or
3672 switch (look_ahead(1)->type) {
3679 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3682 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3687 goto finish_specifiers;
3691 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3692 if (typedef_type == NULL) {
3693 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3694 * declaration, so it doesn't generate 'implicit int' followed by more
3695 * errors later on. */
3696 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3701 errorf(HERE, "%K does not name a type", &token);
3704 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3706 type = allocate_type_zero(TYPE_TYPEDEF);
3707 type->typedeft.typedefe = &entity->typedefe;
3711 if (la1_type == '*')
3712 goto finish_specifiers;
3717 goto finish_specifiers;
3722 type = typedef_type;
3726 /* function specifier */
3728 goto finish_specifiers;
3733 in_gcc_extension = old_gcc_extension;
3735 if (type == NULL || (saw_error && type_specifiers != 0)) {
3736 atomic_type_kind_t atomic_type;
3738 /* match valid basic types */
3739 switch (type_specifiers) {
3740 case SPECIFIER_VOID:
3741 atomic_type = ATOMIC_TYPE_VOID;
3743 case SPECIFIER_CHAR:
3744 atomic_type = ATOMIC_TYPE_CHAR;
3746 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3747 atomic_type = ATOMIC_TYPE_SCHAR;
3749 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3750 atomic_type = ATOMIC_TYPE_UCHAR;
3752 case SPECIFIER_SHORT:
3753 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3754 case SPECIFIER_SHORT | SPECIFIER_INT:
3755 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3756 atomic_type = ATOMIC_TYPE_SHORT;
3758 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3759 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3760 atomic_type = ATOMIC_TYPE_USHORT;
3763 case SPECIFIER_SIGNED:
3764 case SPECIFIER_SIGNED | SPECIFIER_INT:
3765 atomic_type = ATOMIC_TYPE_INT;
3767 case SPECIFIER_UNSIGNED:
3768 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3769 atomic_type = ATOMIC_TYPE_UINT;
3771 case SPECIFIER_LONG:
3772 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3773 case SPECIFIER_LONG | SPECIFIER_INT:
3774 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3775 atomic_type = ATOMIC_TYPE_LONG;
3777 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3778 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3779 atomic_type = ATOMIC_TYPE_ULONG;
3782 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3783 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3784 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3785 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3787 atomic_type = ATOMIC_TYPE_LONGLONG;
3788 goto warn_about_long_long;
3790 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3791 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3793 atomic_type = ATOMIC_TYPE_ULONGLONG;
3794 warn_about_long_long:
3795 if (warning.long_long) {
3796 warningf(&specifiers->source_position,
3797 "ISO C90 does not support 'long long'");
3801 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3802 atomic_type = unsigned_int8_type_kind;
3805 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3806 atomic_type = unsigned_int16_type_kind;
3809 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3810 atomic_type = unsigned_int32_type_kind;
3813 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3814 atomic_type = unsigned_int64_type_kind;
3817 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3818 atomic_type = unsigned_int128_type_kind;
3821 case SPECIFIER_INT8:
3822 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3823 atomic_type = int8_type_kind;
3826 case SPECIFIER_INT16:
3827 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3828 atomic_type = int16_type_kind;
3831 case SPECIFIER_INT32:
3832 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3833 atomic_type = int32_type_kind;
3836 case SPECIFIER_INT64:
3837 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3838 atomic_type = int64_type_kind;
3841 case SPECIFIER_INT128:
3842 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3843 atomic_type = int128_type_kind;
3846 case SPECIFIER_FLOAT:
3847 atomic_type = ATOMIC_TYPE_FLOAT;
3849 case SPECIFIER_DOUBLE:
3850 atomic_type = ATOMIC_TYPE_DOUBLE;
3852 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3853 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3855 case SPECIFIER_BOOL:
3856 atomic_type = ATOMIC_TYPE_BOOL;
3858 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3859 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3860 atomic_type = ATOMIC_TYPE_FLOAT;
3862 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3863 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3864 atomic_type = ATOMIC_TYPE_DOUBLE;
3866 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3867 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3868 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3871 /* invalid specifier combination, give an error message */
3872 if (type_specifiers == 0) {
3876 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3877 if (!(c_mode & _CXX) && !strict_mode) {
3878 if (warning.implicit_int) {
3879 warningf(HERE, "no type specifiers in declaration, using 'int'");
3881 atomic_type = ATOMIC_TYPE_INT;
3884 errorf(HERE, "no type specifiers given in declaration");
3886 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3887 (type_specifiers & SPECIFIER_UNSIGNED)) {
3888 errorf(HERE, "signed and unsigned specifiers given");
3889 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3890 errorf(HERE, "only integer types can be signed or unsigned");
3892 errorf(HERE, "multiple datatypes in declaration");
3897 if (type_specifiers & SPECIFIER_COMPLEX) {
3898 type = allocate_type_zero(TYPE_COMPLEX);
3899 type->complex.akind = atomic_type;
3900 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3901 type = allocate_type_zero(TYPE_IMAGINARY);
3902 type->imaginary.akind = atomic_type;
3904 type = allocate_type_zero(TYPE_ATOMIC);
3905 type->atomic.akind = atomic_type;
3908 } else if (type_specifiers != 0) {
3909 errorf(HERE, "multiple datatypes in declaration");
3912 /* FIXME: check type qualifiers here */
3914 type->base.qualifiers = qualifiers;
3915 type->base.modifiers = modifiers;
3917 type_t *result = typehash_insert(type);
3918 if (newtype && result != type) {
3922 specifiers->type = result;
3926 specifiers->type = type_error_type;
3930 static type_qualifiers_t parse_type_qualifiers(void)
3932 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3935 switch (token.type) {
3936 /* type qualifiers */
3937 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3938 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3939 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3940 /* microsoft extended type modifiers */
3941 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3942 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3943 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3944 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3945 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3954 * Parses an K&R identifier list
3956 static void parse_identifier_list(scope_t *scope)
3959 entity_t *entity = allocate_entity_zero(ENTITY_VARIABLE);
3960 entity->base.source_position = token.source_position;
3961 entity->base.namespc = NAMESPACE_NORMAL;
3962 entity->base.symbol = token.v.symbol;
3963 /* a K&R parameter has no type, yet */
3966 append_entity(scope, entity);
3968 if (token.type != ',') {
3972 } while (token.type == T_IDENTIFIER);
3975 static type_t *automatic_type_conversion(type_t *orig_type);
3977 static void semantic_parameter(declaration_t *declaration)
3979 /* TODO: improve error messages */
3980 source_position_t const* const pos = &declaration->base.source_position;
3983 switch (declaration->declared_storage_class) {
3984 /* Allowed storage classes */
3985 case STORAGE_CLASS_NONE:
3986 case STORAGE_CLASS_REGISTER:
3990 errorf(pos, "parameter may only have none or register storage class");
3994 type_t *const orig_type = declaration->type;
3995 /* §6.7.5.3(7): Array as last part of a parameter type is just syntactic
3996 * sugar. Turn it into a pointer.
3997 * §6.7.5.3(8): A declaration of a parameter as ``function returning type''
3998 * shall be adjusted to ``pointer to function returning type'', as in 6.3.2.1.
4000 type_t *const type = automatic_type_conversion(orig_type);
4001 declaration->type = type;
4003 if (is_type_incomplete(skip_typeref(type))) {
4004 errorf(pos, "parameter '%#T' is of incomplete type",
4005 orig_type, declaration->base.symbol);
4009 static entity_t *parse_parameter(void)
4011 declaration_specifiers_t specifiers;
4012 memset(&specifiers, 0, sizeof(specifiers));
4014 parse_declaration_specifiers(&specifiers);
4016 entity_t *entity = parse_declarator(&specifiers, true, false);
4021 * Parses function type parameters (and optionally creates variable_t entities
4022 * for them in a scope)
4024 static void parse_parameters(function_type_t *type, scope_t *scope)
4027 add_anchor_token(')');
4028 int saved_comma_state = save_and_reset_anchor_state(',');
4030 if (token.type == T_IDENTIFIER &&
4031 !is_typedef_symbol(token.v.symbol)) {
4032 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
4033 if (la1_type == ',' || la1_type == ')') {
4034 type->kr_style_parameters = true;
4035 parse_identifier_list(scope);
4036 goto parameters_finished;
4040 if (token.type == ')') {
4041 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
4042 if (!(c_mode & _CXX))
4043 type->unspecified_parameters = true;
4044 goto parameters_finished;
4047 function_parameter_t *parameter;
4048 function_parameter_t *last_parameter = NULL;
4051 switch (token.type) {
4054 type->variadic = true;
4055 goto parameters_finished;
4058 case T___extension__:
4061 entity_t *entity = parse_parameter();
4062 if (entity->kind == ENTITY_TYPEDEF) {
4063 errorf(&entity->base.source_position,
4064 "typedef not allowed as function parameter");
4067 assert(is_declaration(entity));
4069 /* func(void) is not a parameter */
4070 if (last_parameter == NULL
4071 && token.type == ')'
4072 && entity->base.symbol == NULL
4073 && skip_typeref(entity->declaration.type) == type_void) {
4074 goto parameters_finished;
4076 semantic_parameter(&entity->declaration);
4078 parameter = obstack_alloc(type_obst, sizeof(parameter[0]));
4079 memset(parameter, 0, sizeof(parameter[0]));
4080 parameter->type = entity->declaration.type;
4082 if (scope != NULL) {
4083 append_entity(scope, entity);
4086 if (last_parameter != NULL) {
4087 last_parameter->next = parameter;
4089 type->parameters = parameter;
4091 last_parameter = parameter;
4096 goto parameters_finished;
4098 if (token.type != ',') {
4099 goto parameters_finished;
4105 parameters_finished:
4106 rem_anchor_token(')');
4110 restore_anchor_state(',', saved_comma_state);
4113 typedef enum construct_type_kind_t {
4118 } construct_type_kind_t;
4120 typedef struct construct_type_t construct_type_t;
4121 struct construct_type_t {
4122 construct_type_kind_t kind;
4123 construct_type_t *next;
4126 typedef struct parsed_pointer_t parsed_pointer_t;
4127 struct parsed_pointer_t {
4128 construct_type_t construct_type;
4129 type_qualifiers_t type_qualifiers;
4132 typedef struct construct_function_type_t construct_function_type_t;
4133 struct construct_function_type_t {
4134 construct_type_t construct_type;
4135 type_t *function_type;
4138 typedef struct parsed_array_t parsed_array_t;
4139 struct parsed_array_t {
4140 construct_type_t construct_type;
4141 type_qualifiers_t type_qualifiers;
4147 typedef struct construct_base_type_t construct_base_type_t;
4148 struct construct_base_type_t {
4149 construct_type_t construct_type;
4153 static construct_type_t *parse_pointer_declarator(void)
4157 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
4158 memset(pointer, 0, sizeof(pointer[0]));
4159 pointer->construct_type.kind = CONSTRUCT_POINTER;
4160 pointer->type_qualifiers = parse_type_qualifiers();
4162 return (construct_type_t*) pointer;
4165 static construct_type_t *parse_array_declarator(void)
4168 add_anchor_token(']');
4170 parsed_array_t *array = obstack_alloc(&temp_obst, sizeof(array[0]));
4171 memset(array, 0, sizeof(array[0]));
4172 array->construct_type.kind = CONSTRUCT_ARRAY;
4174 if (token.type == T_static) {
4175 array->is_static = true;
4179 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
4180 if (type_qualifiers != 0) {
4181 if (token.type == T_static) {
4182 array->is_static = true;
4186 array->type_qualifiers = type_qualifiers;
4188 if (token.type == '*' && look_ahead(1)->type == ']') {
4189 array->is_variable = true;
4191 } else if (token.type != ']') {
4192 array->size = parse_assignment_expression();
4195 rem_anchor_token(']');
4199 return (construct_type_t*) array;
4202 static construct_type_t *parse_function_declarator(scope_t *scope)
4204 type_t *type = allocate_type_zero(TYPE_FUNCTION);
4206 /* TODO: revive this... once we know exactly how to do it */
4208 decl_modifiers_t modifiers = entity->declaration.modifiers;
4210 unsigned mask = modifiers & (DM_CDECL|DM_STDCALL|DM_FASTCALL|DM_THISCALL);
4212 if (mask & (mask-1)) {
4213 const char *first = NULL, *second = NULL;
4215 /* more than one calling convention set */
4216 if (modifiers & DM_CDECL) {
4217 if (first == NULL) first = "cdecl";
4218 else if (second == NULL) second = "cdecl";
4220 if (modifiers & DM_STDCALL) {
4221 if (first == NULL) first = "stdcall";
4222 else if (second == NULL) second = "stdcall";
4224 if (modifiers & DM_FASTCALL) {
4225 if (first == NULL) first = "fastcall";
4226 else if (second == NULL) second = "fastcall";
4228 if (modifiers & DM_THISCALL) {
4229 if (first == NULL) first = "thiscall";
4230 else if (second == NULL) second = "thiscall";
4232 errorf(&entity->base.source_position,
4233 "%s and %s attributes are not compatible", first, second);
4236 if (modifiers & DM_CDECL)
4237 type->function.calling_convention = CC_CDECL;
4238 else if (modifiers & DM_STDCALL)
4239 type->function.calling_convention = CC_STDCALL;
4240 else if (modifiers & DM_FASTCALL)
4241 type->function.calling_convention = CC_FASTCALL;
4242 else if (modifiers & DM_THISCALL)
4243 type->function.calling_convention = CC_THISCALL;
4246 parse_parameters(&type->function, scope);
4248 construct_function_type_t *construct_function_type =
4249 obstack_alloc(&temp_obst, sizeof(construct_function_type[0]));
4250 memset(construct_function_type, 0, sizeof(construct_function_type[0]));
4251 construct_function_type->construct_type.kind = CONSTRUCT_FUNCTION;
4252 construct_function_type->function_type = type;
4254 return &construct_function_type->construct_type;
4257 typedef struct parse_declarator_env_t {
4258 decl_modifiers_t modifiers;
4260 source_position_t source_position;
4262 } parse_declarator_env_t;
4264 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env,
4265 bool may_be_abstract)
4267 /* construct a single linked list of construct_type_t's which describe
4268 * how to construct the final declarator type */
4269 construct_type_t *first = NULL;
4270 construct_type_t *last = NULL;
4271 gnu_attribute_t *attributes = NULL;
4273 decl_modifiers_t modifiers = parse_attributes(&attributes);
4276 while (token.type == '*') {
4277 construct_type_t *type = parse_pointer_declarator();
4287 /* TODO: find out if this is correct */
4288 modifiers |= parse_attributes(&attributes);
4292 env->modifiers |= modifiers;
4294 construct_type_t *inner_types = NULL;
4296 switch (token.type) {
4299 errorf(HERE, "no identifier expected in typename");
4301 env->symbol = token.v.symbol;
4302 env->source_position = token.source_position;
4308 add_anchor_token(')');
4309 inner_types = parse_inner_declarator(env, may_be_abstract);
4310 if (inner_types != NULL) {
4311 /* All later declarators only modify the return type */
4314 rem_anchor_token(')');
4318 if (may_be_abstract)
4320 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
4325 construct_type_t *p = last;
4328 construct_type_t *type;
4329 switch (token.type) {
4331 scope_t *scope = NULL;
4333 scope = &env->parameters;
4335 type = parse_function_declarator(scope);
4339 type = parse_array_declarator();
4342 goto declarator_finished;
4345 /* insert in the middle of the list (behind p) */
4347 type->next = p->next;
4358 declarator_finished:
4359 /* append inner_types at the end of the list, we don't to set last anymore
4360 * as it's not needed anymore */
4362 assert(first == NULL);
4363 first = inner_types;
4365 last->next = inner_types;
4373 static void parse_declaration_attributes(entity_t *entity)
4375 gnu_attribute_t *attributes = NULL;
4376 decl_modifiers_t modifiers = parse_attributes(&attributes);
4382 if (entity->kind == ENTITY_TYPEDEF) {
4383 modifiers |= entity->typedefe.modifiers;
4384 type = entity->typedefe.type;
4386 assert(is_declaration(entity));
4387 modifiers |= entity->declaration.modifiers;
4388 type = entity->declaration.type;
4393 /* handle these strange/stupid mode attributes */
4394 gnu_attribute_t *attribute = attributes;
4395 for ( ; attribute != NULL; attribute = attribute->next) {
4396 if (attribute->kind != GNU_AK_MODE || attribute->invalid)
4399 atomic_type_kind_t akind = attribute->u.akind;
4400 if (!is_type_signed(type)) {
4402 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_UCHAR; break;
4403 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_USHORT; break;
4404 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_UINT; break;
4405 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_ULONGLONG; break;
4407 panic("invalid akind in mode attribute");
4411 case ATOMIC_TYPE_CHAR: akind = ATOMIC_TYPE_SCHAR; break;
4412 case ATOMIC_TYPE_SHORT: akind = ATOMIC_TYPE_SHORT; break;
4413 case ATOMIC_TYPE_INT: akind = ATOMIC_TYPE_INT; break;
4414 case ATOMIC_TYPE_LONGLONG: akind = ATOMIC_TYPE_LONGLONG; break;
4416 panic("invalid akind in mode attribute");
4420 type = make_atomic_type(akind, type->base.qualifiers);
4423 type_modifiers_t type_modifiers = type->base.modifiers;
4424 if (modifiers & DM_TRANSPARENT_UNION)
4425 modifiers |= TYPE_MODIFIER_TRANSPARENT_UNION;
4427 if (type->base.modifiers != type_modifiers) {
4428 type_t *copy = duplicate_type(type);
4429 copy->base.modifiers = type_modifiers;
4431 type = typehash_insert(copy);
4433 obstack_free(type_obst, copy);
4437 if (entity->kind == ENTITY_TYPEDEF) {
4438 entity->typedefe.type = type;
4439 entity->typedefe.modifiers = modifiers;
4441 entity->declaration.type = type;
4442 entity->declaration.modifiers = modifiers;
4446 static type_t *construct_declarator_type(construct_type_t *construct_list,
4449 construct_type_t *iter = construct_list;
4450 for( ; iter != NULL; iter = iter->next) {
4451 switch (iter->kind) {
4452 case CONSTRUCT_INVALID:
4453 internal_errorf(HERE, "invalid type construction found");
4454 case CONSTRUCT_FUNCTION: {
4455 construct_function_type_t *construct_function_type
4456 = (construct_function_type_t*) iter;
4458 type_t *function_type = construct_function_type->function_type;
4460 function_type->function.return_type = type;
4462 type_t *skipped_return_type = skip_typeref(type);
4464 if (is_type_function(skipped_return_type)) {
4465 errorf(HERE, "function returning function is not allowed");
4466 } else if (is_type_array(skipped_return_type)) {
4467 errorf(HERE, "function returning array is not allowed");
4469 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4471 "type qualifiers in return type of function type are meaningless");
4475 type = function_type;
4479 case CONSTRUCT_POINTER: {
4480 parsed_pointer_t *parsed_pointer = (parsed_pointer_t*) iter;
4481 type = make_pointer_type(type, parsed_pointer->type_qualifiers);
4485 case CONSTRUCT_ARRAY: {
4486 parsed_array_t *parsed_array = (parsed_array_t*) iter;
4487 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4489 expression_t *size_expression = parsed_array->size;
4490 if (size_expression != NULL) {
4492 = create_implicit_cast(size_expression, type_size_t);
4495 array_type->base.qualifiers = parsed_array->type_qualifiers;
4496 array_type->array.element_type = type;
4497 array_type->array.is_static = parsed_array->is_static;
4498 array_type->array.is_variable = parsed_array->is_variable;
4499 array_type->array.size_expression = size_expression;
4501 if (size_expression != NULL) {
4502 if (is_constant_expression(size_expression)) {
4503 array_type->array.size_constant = true;
4504 array_type->array.size
4505 = fold_constant(size_expression);
4507 array_type->array.is_vla = true;
4511 type_t *skipped_type = skip_typeref(type);
4513 if (is_type_incomplete(skipped_type)) {
4514 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4515 } else if (is_type_function(skipped_type)) {
4516 errorf(HERE, "array of functions is not allowed");
4523 type_t *hashed_type = typehash_insert(type);
4524 if (hashed_type != type) {
4525 /* the function type was constructed earlier freeing it here will
4526 * destroy other types... */
4527 if (iter->kind != CONSTRUCT_FUNCTION) {
4537 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4538 bool may_be_abstract,
4539 bool create_compound_member)
4541 parse_declarator_env_t env;
4542 memset(&env, 0, sizeof(env));
4544 construct_type_t *construct_type
4545 = parse_inner_declarator(&env, may_be_abstract);
4546 type_t *type = construct_declarator_type(construct_type, specifiers->type);
4548 if (construct_type != NULL) {
4549 obstack_free(&temp_obst, construct_type);
4553 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4554 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4555 entity->base.symbol = env.symbol;
4556 entity->base.source_position = env.source_position;
4557 entity->typedefe.type = type;
4559 if (create_compound_member) {
4560 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4561 } else if (is_type_function(skip_typeref(type))) {
4562 entity = allocate_entity_zero(ENTITY_FUNCTION);
4564 entity->function.is_inline = specifiers->is_inline;
4565 entity->function.parameters = env.parameters;
4567 entity = allocate_entity_zero(ENTITY_VARIABLE);
4569 entity->variable.get_property_sym = specifiers->get_property_sym;
4570 entity->variable.put_property_sym = specifiers->put_property_sym;
4571 if (specifiers->alignment != 0) {
4572 /* TODO: add checks here */
4573 entity->variable.alignment = specifiers->alignment;
4576 if (warning.other && specifiers->is_inline && is_type_valid(type)) {
4577 warningf(&env.source_position,
4578 "variable '%Y' declared 'inline'\n", env.symbol);
4582 entity->base.source_position = env.source_position;
4583 entity->base.symbol = env.symbol;
4584 entity->base.namespc = NAMESPACE_NORMAL;
4585 entity->declaration.type = type;
4586 entity->declaration.modifiers = env.modifiers | specifiers->modifiers;
4587 entity->declaration.deprecated_string = specifiers->deprecated_string;
4589 storage_class_t storage_class = specifiers->storage_class;
4590 entity->declaration.declared_storage_class = storage_class;
4592 if (storage_class == STORAGE_CLASS_NONE && scope != file_scope) {
4593 storage_class = STORAGE_CLASS_AUTO;
4595 entity->declaration.storage_class = storage_class;
4598 parse_declaration_attributes(entity);
4603 static type_t *parse_abstract_declarator(type_t *base_type)
4605 construct_type_t *construct_type = parse_inner_declarator(NULL, 1);
4607 type_t *result = construct_declarator_type(construct_type, base_type);
4608 if (construct_type != NULL) {
4609 obstack_free(&temp_obst, construct_type);
4616 * Check if the declaration of main is suspicious. main should be a
4617 * function with external linkage, returning int, taking either zero
4618 * arguments, two, or three arguments of appropriate types, ie.
4620 * int main([ int argc, char **argv [, char **env ] ]).
4622 * @param decl the declaration to check
4623 * @param type the function type of the declaration
4625 static void check_type_of_main(const entity_t *entity)
4627 const source_position_t *pos = &entity->base.source_position;
4628 if (entity->kind != ENTITY_FUNCTION) {
4629 warningf(pos, "'main' is not a function");
4633 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4634 warningf(pos, "'main' is normally a non-static function");
4637 type_t *type = skip_typeref(entity->declaration.type);
4638 assert(is_type_function(type));
4640 function_type_t *func_type = &type->function;
4641 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4642 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4643 func_type->return_type);
4645 const function_parameter_t *parm = func_type->parameters;
4647 type_t *const first_type = parm->type;
4648 if (!types_compatible(skip_typeref(first_type), type_int)) {
4650 "first argument of 'main' should be 'int', but is '%T'",
4655 type_t *const second_type = parm->type;
4656 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4657 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4661 type_t *const third_type = parm->type;
4662 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4663 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4667 goto warn_arg_count;
4671 warningf(pos, "'main' takes only zero, two or three arguments");
4677 * Check if a symbol is the equal to "main".
4679 static bool is_sym_main(const symbol_t *const sym)
4681 return strcmp(sym->string, "main") == 0;
4685 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4686 * for various problems that occur for multiple definitions
4688 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4690 const symbol_t *const symbol = entity->base.symbol;
4691 const namespace_t namespc = entity->base.namespc;
4692 const source_position_t *pos = &entity->base.source_position;
4694 assert(symbol != NULL);
4695 entity_t *previous_entity = get_entity(symbol, namespc);
4696 /* pushing the same entity twice will break the stack structure */
4697 assert(previous_entity != entity);
4699 if (entity->kind == ENTITY_FUNCTION) {
4700 type_t *const orig_type = entity->declaration.type;
4701 type_t *const type = skip_typeref(orig_type);
4703 assert(is_type_function(type));
4704 if (type->function.unspecified_parameters &&
4705 warning.strict_prototypes &&
4706 previous_entity == NULL) {
4707 warningf(pos, "function declaration '%#T' is not a prototype",
4711 if (warning.main && scope == file_scope && is_sym_main(symbol)) {
4712 check_type_of_main(entity);
4716 if (is_declaration(entity)) {
4717 if (warning.nested_externs
4718 && entity->declaration.storage_class == STORAGE_CLASS_EXTERN
4719 && scope != file_scope) {
4720 warningf(pos, "nested extern declaration of '%#T'",
4721 entity->declaration.type, symbol);
4725 if (previous_entity != NULL
4726 && previous_entity->base.parent_scope == ¤t_function->parameters
4727 && scope->depth == previous_entity->base.parent_scope->depth + 1) {
4729 assert(previous_entity->kind == ENTITY_VARIABLE);
4731 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4732 entity->declaration.type, symbol,
4733 previous_entity->declaration.type, symbol,
4734 &previous_entity->base.source_position);
4738 if (previous_entity != NULL
4739 && previous_entity->base.parent_scope == scope) {
4741 if (previous_entity->kind != entity->kind) {
4743 "redeclaration of '%Y' as different kind of symbol (declared %P)",
4744 symbol, &previous_entity->base.source_position);
4747 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4749 "redeclaration of enum entry '%Y' (declared %P)",
4750 symbol, &previous_entity->base.source_position);
4753 if (previous_entity->kind == ENTITY_TYPEDEF) {
4754 /* TODO: C++ allows this for exactly the same type */
4756 "redefinition of typedef '%Y' (declared %P)",
4757 symbol, &previous_entity->base.source_position);
4761 /* at this point we should have only VARIABLES or FUNCTIONS */
4762 assert(is_declaration(previous_entity) && is_declaration(entity));
4764 /* can happen for K&R style declarations */
4765 if (previous_entity->kind == ENTITY_VARIABLE
4766 && previous_entity->declaration.type == NULL
4767 && entity->kind == ENTITY_VARIABLE) {
4768 previous_entity->declaration.type = entity->declaration.type;
4769 previous_entity->declaration.storage_class
4770 = entity->declaration.storage_class;
4771 previous_entity->declaration.declared_storage_class
4772 = entity->declaration.declared_storage_class;
4773 previous_entity->declaration.modifiers
4774 = entity->declaration.modifiers;
4775 previous_entity->declaration.deprecated_string
4776 = entity->declaration.deprecated_string;
4778 assert(entity->declaration.type != NULL);
4780 declaration_t *const previous_declaration
4781 = &previous_entity->declaration;
4782 declaration_t *const declaration = &entity->declaration;
4783 type_t *const orig_type = entity->declaration.type;
4784 type_t *const type = skip_typeref(orig_type);
4786 type_t *prev_type = skip_typeref(previous_declaration->type);
4788 if (!types_compatible(type, prev_type)) {
4790 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4791 orig_type, symbol, previous_declaration->type, symbol,
4792 &previous_entity->base.source_position);
4794 unsigned old_storage_class = previous_declaration->storage_class;
4795 if (warning.redundant_decls && is_definition
4796 && previous_declaration->storage_class == STORAGE_CLASS_STATIC
4797 && !(previous_declaration->modifiers & DM_USED)
4798 && !previous_declaration->used) {
4799 warningf(&previous_entity->base.source_position,
4800 "unnecessary static forward declaration for '%#T'",
4801 previous_declaration->type, symbol);
4804 unsigned new_storage_class = declaration->storage_class;
4805 if (is_type_incomplete(prev_type)) {
4806 previous_declaration->type = type;
4810 /* pretend no storage class means extern for function
4811 * declarations (except if the previous declaration is neither
4812 * none nor extern) */
4813 if (entity->kind == ENTITY_FUNCTION) {
4814 if (prev_type->function.unspecified_parameters) {
4815 previous_declaration->type = type;
4819 switch (old_storage_class) {
4820 case STORAGE_CLASS_NONE:
4821 old_storage_class = STORAGE_CLASS_EXTERN;
4824 case STORAGE_CLASS_EXTERN:
4825 if (is_definition) {
4826 if (warning.missing_prototypes &&
4827 prev_type->function.unspecified_parameters &&
4828 !is_sym_main(symbol)) {
4829 warningf(pos, "no previous prototype for '%#T'",
4832 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4833 new_storage_class = STORAGE_CLASS_EXTERN;
4842 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4843 new_storage_class == STORAGE_CLASS_EXTERN) {
4844 warn_redundant_declaration:
4845 if (!is_definition &&
4846 warning.redundant_decls &&
4847 is_type_valid(prev_type) &&
4848 strcmp(previous_entity->base.source_position.input_name, "<builtin>") != 0) {
4850 "redundant declaration for '%Y' (declared %P)",
4851 symbol, &previous_entity->base.source_position);
4853 } else if (current_function == NULL) {
4854 if (old_storage_class != STORAGE_CLASS_STATIC &&
4855 new_storage_class == STORAGE_CLASS_STATIC) {
4857 "static declaration of '%Y' follows non-static declaration (declared %P)",
4858 symbol, &previous_entity->base.source_position);
4859 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4860 previous_declaration->storage_class = STORAGE_CLASS_NONE;
4861 previous_declaration->declared_storage_class = STORAGE_CLASS_NONE;
4863 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4865 goto error_redeclaration;
4866 goto warn_redundant_declaration;
4868 } else if (is_type_valid(prev_type)) {
4869 if (old_storage_class == new_storage_class) {
4870 error_redeclaration:
4871 errorf(pos, "redeclaration of '%Y' (declared %P)",
4872 symbol, &previous_entity->base.source_position);
4875 "redeclaration of '%Y' with different linkage (declared %P)",
4876 symbol, &previous_entity->base.source_position);
4881 previous_declaration->modifiers |= declaration->modifiers;
4882 if (entity->kind == ENTITY_FUNCTION) {
4883 previous_entity->function.is_inline |= entity->function.is_inline;
4885 return previous_entity;
4888 if (entity->kind == ENTITY_FUNCTION) {
4889 if (is_definition &&
4890 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4891 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4892 warningf(pos, "no previous prototype for '%#T'",
4893 entity->declaration.type, symbol);
4894 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4895 warningf(pos, "no previous declaration for '%#T'",
4896 entity->declaration.type, symbol);
4899 } else if (warning.missing_declarations
4900 && entity->kind == ENTITY_VARIABLE
4901 && scope == file_scope) {
4902 declaration_t *declaration = &entity->declaration;
4903 if (declaration->storage_class == STORAGE_CLASS_NONE ||
4904 declaration->storage_class == STORAGE_CLASS_THREAD) {
4905 warningf(pos, "no previous declaration for '%#T'",
4906 declaration->type, symbol);
4911 assert(entity->base.parent_scope == NULL);
4912 assert(scope != NULL);
4914 entity->base.parent_scope = scope;
4915 entity->base.namespc = NAMESPACE_NORMAL;
4916 environment_push(entity);
4917 append_entity(scope, entity);
4922 static void parser_error_multiple_definition(entity_t *entity,
4923 const source_position_t *source_position)
4925 errorf(source_position, "multiple definition of symbol '%Y' (declared %P)",
4926 entity->base.symbol, &entity->base.source_position);
4929 static bool is_declaration_specifier(const token_t *token,
4930 bool only_specifiers_qualifiers)
4932 switch (token->type) {
4937 return is_typedef_symbol(token->v.symbol);
4939 case T___extension__:
4941 return !only_specifiers_qualifiers;
4948 static void parse_init_declarator_rest(entity_t *entity)
4950 assert(is_declaration(entity));
4951 declaration_t *const declaration = &entity->declaration;
4955 type_t *orig_type = declaration->type;
4956 type_t *type = skip_typeref(orig_type);
4958 if (entity->kind == ENTITY_VARIABLE
4959 && entity->variable.initializer != NULL) {
4960 parser_error_multiple_definition(entity, HERE);
4963 bool must_be_constant = false;
4964 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4965 declaration->storage_class == STORAGE_CLASS_THREAD_STATIC ||
4966 entity->base.parent_scope == file_scope) {
4967 must_be_constant = true;
4970 if (is_type_function(type)) {
4971 errorf(&entity->base.source_position,
4972 "function '%#T' is initialized like a variable",
4973 orig_type, entity->base.symbol);
4974 orig_type = type_error_type;
4977 parse_initializer_env_t env;
4978 env.type = orig_type;
4979 env.must_be_constant = must_be_constant;
4980 env.entity = entity;
4981 current_init_decl = entity;
4983 initializer_t *initializer = parse_initializer(&env);
4984 current_init_decl = NULL;
4986 if (entity->kind == ENTITY_VARIABLE) {
4987 /* § 6.7.5 (22) array initializers for arrays with unknown size
4988 * determine the array type size */
4989 declaration->type = env.type;
4990 entity->variable.initializer = initializer;
4994 /* parse rest of a declaration without any declarator */
4995 static void parse_anonymous_declaration_rest(
4996 const declaration_specifiers_t *specifiers)
5000 if (warning.other) {
5001 if (specifiers->storage_class != STORAGE_CLASS_NONE) {
5002 warningf(&specifiers->source_position,
5003 "useless storage class in empty declaration");
5006 type_t *type = specifiers->type;
5007 switch (type->kind) {
5008 case TYPE_COMPOUND_STRUCT:
5009 case TYPE_COMPOUND_UNION: {
5010 if (type->compound.compound->base.symbol == NULL) {
5011 warningf(&specifiers->source_position,
5012 "unnamed struct/union that defines no instances");
5021 warningf(&specifiers->source_position, "empty declaration");
5027 static void parse_declaration_rest(entity_t *ndeclaration,
5028 const declaration_specifiers_t *specifiers,
5029 parsed_declaration_func finished_declaration)
5031 add_anchor_token(';');
5032 add_anchor_token(',');
5034 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
5036 if (token.type == '=') {
5037 parse_init_declarator_rest(entity);
5040 if (token.type != ',')
5044 add_anchor_token('=');
5045 ndeclaration = parse_declarator(specifiers, /*may_be_abstract=*/false, false);
5046 rem_anchor_token('=');
5051 rem_anchor_token(';');
5052 rem_anchor_token(',');
5055 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
5057 symbol_t *symbol = entity->base.symbol;
5058 if (symbol == NULL) {
5059 errorf(HERE, "anonymous declaration not valid as function parameter");
5063 assert(entity->base.namespc == NAMESPACE_NORMAL);
5064 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
5065 if (previous_entity == NULL
5066 || previous_entity->base.parent_scope != scope) {
5067 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
5072 if (is_definition) {
5073 errorf(HERE, "parameter %Y is initialised", entity->base.symbol);
5076 return record_entity(entity, false);
5079 static void parse_declaration(parsed_declaration_func finished_declaration)
5081 declaration_specifiers_t specifiers;
5082 memset(&specifiers, 0, sizeof(specifiers));
5084 add_anchor_token(';');
5085 parse_declaration_specifiers(&specifiers);
5086 rem_anchor_token(';');
5088 if (token.type == ';') {
5089 parse_anonymous_declaration_rest(&specifiers);
5091 entity_t *entity = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5092 parse_declaration_rest(entity, &specifiers, finished_declaration);
5096 static type_t *get_default_promoted_type(type_t *orig_type)
5098 type_t *result = orig_type;
5100 type_t *type = skip_typeref(orig_type);
5101 if (is_type_integer(type)) {
5102 result = promote_integer(type);
5103 } else if (type == type_float) {
5104 result = type_double;
5110 static void parse_kr_declaration_list(entity_t *entity)
5112 if (entity->kind != ENTITY_FUNCTION)
5115 type_t *type = skip_typeref(entity->declaration.type);
5116 assert(is_type_function(type));
5117 if (!type->function.kr_style_parameters)
5121 add_anchor_token('{');
5123 /* push function parameters */
5124 size_t const top = environment_top();
5125 scope_push(&entity->function.parameters);
5127 entity_t *parameter = entity->function.parameters.entities;
5128 for ( ; parameter != NULL; parameter = parameter->base.next) {
5129 assert(parameter->base.parent_scope == NULL);
5130 parameter->base.parent_scope = scope;
5131 environment_push(parameter);
5134 /* parse declaration list */
5135 while (is_declaration_specifier(&token, false)) {
5136 parse_declaration(finished_kr_declaration);
5139 /* pop function parameters */
5140 assert(scope == &entity->function.parameters);
5142 environment_pop_to(top);
5144 /* update function type */
5145 type_t *new_type = duplicate_type(type);
5147 function_parameter_t *parameters = NULL;
5148 function_parameter_t *last_parameter = NULL;
5150 entity_t *parameter_declaration = entity->function.parameters.entities;
5151 for( ; parameter_declaration != NULL;
5152 parameter_declaration = parameter_declaration->base.next) {
5153 type_t *parameter_type = parameter_declaration->declaration.type;
5154 if (parameter_type == NULL) {
5156 errorf(HERE, "no type specified for function parameter '%Y'",
5157 parameter_declaration->base.symbol);
5159 if (warning.implicit_int) {
5160 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
5161 parameter_declaration->base.symbol);
5163 parameter_type = type_int;
5164 parameter_declaration->declaration.type = parameter_type;
5168 semantic_parameter(¶meter_declaration->declaration);
5169 parameter_type = parameter_declaration->declaration.type;
5172 * we need the default promoted types for the function type
5174 parameter_type = get_default_promoted_type(parameter_type);
5176 function_parameter_t *function_parameter
5177 = obstack_alloc(type_obst, sizeof(function_parameter[0]));
5178 memset(function_parameter, 0, sizeof(function_parameter[0]));
5180 function_parameter->type = parameter_type;
5181 if (last_parameter != NULL) {
5182 last_parameter->next = function_parameter;
5184 parameters = function_parameter;
5186 last_parameter = function_parameter;
5189 /* § 6.9.1.7: A K&R style parameter list does NOT act as a function
5191 new_type->function.parameters = parameters;
5192 new_type->function.unspecified_parameters = true;
5194 type = typehash_insert(new_type);
5195 if (type != new_type) {
5196 obstack_free(type_obst, new_type);
5199 entity->declaration.type = type;
5201 rem_anchor_token('{');
5204 static bool first_err = true;
5207 * When called with first_err set, prints the name of the current function,
5210 static void print_in_function(void)
5214 diagnosticf("%s: In function '%Y':\n",
5215 current_function->base.base.source_position.input_name,
5216 current_function->base.base.symbol);
5221 * Check if all labels are defined in the current function.
5222 * Check if all labels are used in the current function.
5224 static void check_labels(void)
5226 for (const goto_statement_t *goto_statement = goto_first;
5227 goto_statement != NULL;
5228 goto_statement = goto_statement->next) {
5229 /* skip computed gotos */
5230 if (goto_statement->expression != NULL)
5233 label_t *label = goto_statement->label;
5236 if (label->base.source_position.input_name == NULL) {
5237 print_in_function();
5238 errorf(&goto_statement->base.source_position,
5239 "label '%Y' used but not defined", label->base.symbol);
5245 if (warning.unused_label) {
5246 for (const label_statement_t *label_statement = label_first;
5247 label_statement != NULL;
5248 label_statement = label_statement->next) {
5249 label_t *label = label_statement->label;
5251 if (! label->used) {
5252 print_in_function();
5253 warningf(&label_statement->base.source_position,
5254 "label '%Y' defined but not used", label->base.symbol);
5258 label_first = label_last = NULL;
5261 static void warn_unused_decl(entity_t *entity, entity_t *end,
5262 char const *const what)
5264 for (; entity != NULL; entity = entity->base.next) {
5265 if (!is_declaration(entity))
5268 declaration_t *declaration = &entity->declaration;
5269 if (declaration->implicit)
5272 if (!declaration->used) {
5273 print_in_function();
5274 warningf(&entity->base.source_position, "%s '%Y' is unused",
5275 what, entity->base.symbol);
5276 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5277 print_in_function();
5278 warningf(&entity->base.source_position, "%s '%Y' is never read",
5279 what, entity->base.symbol);
5287 static void check_unused_variables(statement_t *const stmt, void *const env)
5291 switch (stmt->kind) {
5292 case STATEMENT_DECLARATION: {
5293 declaration_statement_t const *const decls = &stmt->declaration;
5294 warn_unused_decl(decls->declarations_begin, decls->declarations_end,
5300 warn_unused_decl(stmt->fors.scope.entities, NULL, "variable");
5309 * Check declarations of current_function for unused entities.
5311 static void check_declarations(void)
5313 if (warning.unused_parameter) {
5314 const scope_t *scope = ¤t_function->parameters;
5316 /* do not issue unused warnings for main */
5317 if (!is_sym_main(current_function->base.base.symbol)) {
5318 warn_unused_decl(scope->entities, NULL, "parameter");
5321 if (warning.unused_variable) {
5322 walk_statements(current_function->statement, check_unused_variables,
5327 static int determine_truth(expression_t const* const cond)
5330 !is_constant_expression(cond) ? 0 :
5331 fold_constant(cond) != 0 ? 1 :
5335 static bool expression_returns(expression_t const *const expr)
5337 switch (expr->kind) {
5339 expression_t const *const func = expr->call.function;
5340 if (func->kind == EXPR_REFERENCE) {
5341 entity_t *entity = func->reference.entity;
5342 if (entity->kind == ENTITY_FUNCTION
5343 && entity->declaration.modifiers & DM_NORETURN)
5347 if (!expression_returns(func))
5350 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5351 if (!expression_returns(arg->expression))
5358 case EXPR_REFERENCE:
5359 case EXPR_REFERENCE_ENUM_VALUE:
5361 case EXPR_CHARACTER_CONSTANT:
5362 case EXPR_WIDE_CHARACTER_CONSTANT:
5363 case EXPR_STRING_LITERAL:
5364 case EXPR_WIDE_STRING_LITERAL:
5365 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5366 case EXPR_LABEL_ADDRESS:
5367 case EXPR_CLASSIFY_TYPE:
5368 case EXPR_SIZEOF: // TODO handle obscure VLA case
5371 case EXPR_BUILTIN_SYMBOL:
5372 case EXPR_BUILTIN_CONSTANT_P:
5373 case EXPR_BUILTIN_PREFETCH:
5376 case EXPR_STATEMENT: // TODO implement
5379 case EXPR_CONDITIONAL:
5380 // TODO handle constant expression
5382 expression_returns(expr->conditional.condition) && (
5383 expression_returns(expr->conditional.true_expression) ||
5384 expression_returns(expr->conditional.false_expression)
5388 return expression_returns(expr->select.compound);
5390 case EXPR_ARRAY_ACCESS:
5392 expression_returns(expr->array_access.array_ref) &&
5393 expression_returns(expr->array_access.index);
5396 return expression_returns(expr->va_starte.ap);
5399 return expression_returns(expr->va_arge.ap);
5401 EXPR_UNARY_CASES_MANDATORY
5402 return expression_returns(expr->unary.value);
5404 case EXPR_UNARY_THROW:
5408 // TODO handle constant lhs of && and ||
5410 expression_returns(expr->binary.left) &&
5411 expression_returns(expr->binary.right);
5417 panic("unhandled expression");
5420 static bool noreturn_candidate;
5422 static void check_reachable(statement_t *const stmt)
5424 if (stmt->base.reachable)
5426 if (stmt->kind != STATEMENT_DO_WHILE)
5427 stmt->base.reachable = true;
5429 statement_t *last = stmt;
5431 switch (stmt->kind) {
5432 case STATEMENT_INVALID:
5433 case STATEMENT_EMPTY:
5434 case STATEMENT_DECLARATION:
5435 case STATEMENT_LOCAL_LABEL:
5437 next = stmt->base.next;
5440 case STATEMENT_COMPOUND:
5441 next = stmt->compound.statements;
5444 case STATEMENT_RETURN:
5445 noreturn_candidate = false;
5448 case STATEMENT_IF: {
5449 if_statement_t const* const ifs = &stmt->ifs;
5450 int const val = determine_truth(ifs->condition);
5453 check_reachable(ifs->true_statement);
5458 if (ifs->false_statement != NULL) {
5459 check_reachable(ifs->false_statement);
5463 next = stmt->base.next;
5467 case STATEMENT_SWITCH: {
5468 switch_statement_t const *const switchs = &stmt->switchs;
5469 expression_t const *const expr = switchs->expression;
5471 if (is_constant_expression(expr)) {
5472 long const val = fold_constant(expr);
5473 case_label_statement_t * defaults = NULL;
5474 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5475 if (i->expression == NULL) {
5480 if (i->first_case <= val && val <= i->last_case) {
5481 check_reachable((statement_t*)i);
5486 if (defaults != NULL) {
5487 check_reachable((statement_t*)defaults);
5491 bool has_default = false;
5492 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5493 if (i->expression == NULL)
5496 check_reachable((statement_t*)i);
5503 next = stmt->base.next;
5507 case STATEMENT_EXPRESSION: {
5508 /* Check for noreturn function call */
5509 expression_t const *const expr = stmt->expression.expression;
5510 if (!expression_returns(expr))
5513 next = stmt->base.next;
5517 case STATEMENT_CONTINUE: {
5518 statement_t *parent = stmt;
5520 parent = parent->base.parent;
5521 if (parent == NULL) /* continue not within loop */
5525 switch (parent->kind) {
5526 case STATEMENT_WHILE: goto continue_while;
5527 case STATEMENT_DO_WHILE: goto continue_do_while;
5528 case STATEMENT_FOR: goto continue_for;
5535 case STATEMENT_BREAK: {
5536 statement_t *parent = stmt;
5538 parent = parent->base.parent;
5539 if (parent == NULL) /* break not within loop/switch */
5542 switch (parent->kind) {
5543 case STATEMENT_SWITCH:
5544 case STATEMENT_WHILE:
5545 case STATEMENT_DO_WHILE:
5548 next = parent->base.next;
5549 goto found_break_parent;
5558 case STATEMENT_GOTO:
5559 if (stmt->gotos.expression) {
5560 statement_t *parent = stmt->base.parent;
5561 if (parent == NULL) /* top level goto */
5565 next = stmt->gotos.label->statement;
5566 if (next == NULL) /* missing label */
5571 case STATEMENT_LABEL:
5572 next = stmt->label.statement;
5575 case STATEMENT_CASE_LABEL:
5576 next = stmt->case_label.statement;
5579 case STATEMENT_WHILE: {
5580 while_statement_t const *const whiles = &stmt->whiles;
5581 int const val = determine_truth(whiles->condition);
5584 check_reachable(whiles->body);
5589 next = stmt->base.next;
5593 case STATEMENT_DO_WHILE:
5594 next = stmt->do_while.body;
5597 case STATEMENT_FOR: {
5598 for_statement_t *const fors = &stmt->fors;
5600 if (fors->condition_reachable)
5602 fors->condition_reachable = true;
5604 expression_t const *const cond = fors->condition;
5606 cond == NULL ? 1 : determine_truth(cond);
5609 check_reachable(fors->body);
5614 next = stmt->base.next;
5618 case STATEMENT_MS_TRY: {
5619 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5620 check_reachable(ms_try->try_statement);
5621 next = ms_try->final_statement;
5625 case STATEMENT_LEAVE: {
5626 statement_t *parent = stmt;
5628 parent = parent->base.parent;
5629 if (parent == NULL) /* __leave not within __try */
5632 if (parent->kind == STATEMENT_MS_TRY) {
5634 next = parent->ms_try.final_statement;
5642 while (next == NULL) {
5643 next = last->base.parent;
5645 noreturn_candidate = false;
5647 type_t *const type = current_function->base.type;
5648 assert(is_type_function(type));
5649 type_t *const ret = skip_typeref(type->function.return_type);
5650 if (warning.return_type &&
5651 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5652 is_type_valid(ret) &&
5653 !is_sym_main(current_function->base.base.symbol)) {
5654 warningf(&stmt->base.source_position,
5655 "control reaches end of non-void function");
5660 switch (next->kind) {
5661 case STATEMENT_INVALID:
5662 case STATEMENT_EMPTY:
5663 case STATEMENT_DECLARATION:
5664 case STATEMENT_LOCAL_LABEL:
5665 case STATEMENT_EXPRESSION:
5667 case STATEMENT_RETURN:
5668 case STATEMENT_CONTINUE:
5669 case STATEMENT_BREAK:
5670 case STATEMENT_GOTO:
5671 case STATEMENT_LEAVE:
5672 panic("invalid control flow in function");
5674 case STATEMENT_COMPOUND:
5676 case STATEMENT_SWITCH:
5677 case STATEMENT_LABEL:
5678 case STATEMENT_CASE_LABEL:
5680 next = next->base.next;
5683 case STATEMENT_WHILE: {
5685 if (next->base.reachable)
5687 next->base.reachable = true;
5689 while_statement_t const *const whiles = &next->whiles;
5690 int const val = determine_truth(whiles->condition);
5693 check_reachable(whiles->body);
5699 next = next->base.next;
5703 case STATEMENT_DO_WHILE: {
5705 if (next->base.reachable)
5707 next->base.reachable = true;
5709 do_while_statement_t const *const dw = &next->do_while;
5710 int const val = determine_truth(dw->condition);
5713 check_reachable(dw->body);
5719 next = next->base.next;
5723 case STATEMENT_FOR: {
5725 for_statement_t *const fors = &next->fors;
5727 fors->step_reachable = true;
5729 if (fors->condition_reachable)
5731 fors->condition_reachable = true;
5733 expression_t const *const cond = fors->condition;
5735 cond == NULL ? 1 : determine_truth(cond);
5738 check_reachable(fors->body);
5744 next = next->base.next;
5748 case STATEMENT_MS_TRY:
5750 next = next->ms_try.final_statement;
5755 check_reachable(next);
5758 static void check_unreachable(statement_t* const stmt, void *const env)
5762 switch (stmt->kind) {
5763 case STATEMENT_DO_WHILE:
5764 if (!stmt->base.reachable) {
5765 expression_t const *const cond = stmt->do_while.condition;
5766 if (determine_truth(cond) >= 0) {
5767 warningf(&cond->base.source_position,
5768 "condition of do-while-loop is unreachable");
5773 case STATEMENT_FOR: {
5774 for_statement_t const* const fors = &stmt->fors;
5776 // if init and step are unreachable, cond is unreachable, too
5777 if (!stmt->base.reachable && !fors->step_reachable) {
5778 warningf(&stmt->base.source_position, "statement is unreachable");
5780 if (!stmt->base.reachable && fors->initialisation != NULL) {
5781 warningf(&fors->initialisation->base.source_position,
5782 "initialisation of for-statement is unreachable");
5785 if (!fors->condition_reachable && fors->condition != NULL) {
5786 warningf(&fors->condition->base.source_position,
5787 "condition of for-statement is unreachable");
5790 if (!fors->step_reachable && fors->step != NULL) {
5791 warningf(&fors->step->base.source_position,
5792 "step of for-statement is unreachable");
5798 case STATEMENT_COMPOUND:
5799 if (stmt->compound.statements != NULL)
5804 if (!stmt->base.reachable)
5805 warningf(&stmt->base.source_position, "statement is unreachable");
5810 static void parse_external_declaration(void)
5812 /* function-definitions and declarations both start with declaration
5814 declaration_specifiers_t specifiers;
5815 memset(&specifiers, 0, sizeof(specifiers));
5817 add_anchor_token(';');
5818 parse_declaration_specifiers(&specifiers);
5819 rem_anchor_token(';');
5821 /* must be a declaration */
5822 if (token.type == ';') {
5823 parse_anonymous_declaration_rest(&specifiers);
5827 add_anchor_token(',');
5828 add_anchor_token('=');
5829 add_anchor_token(';');
5830 add_anchor_token('{');
5832 /* declarator is common to both function-definitions and declarations */
5833 entity_t *ndeclaration = parse_declarator(&specifiers, /*may_be_abstract=*/false, false);
5835 rem_anchor_token('{');
5836 rem_anchor_token(';');
5837 rem_anchor_token('=');
5838 rem_anchor_token(',');
5840 /* must be a declaration */
5841 switch (token.type) {
5845 parse_declaration_rest(ndeclaration, &specifiers, record_entity);
5849 /* must be a function definition */
5850 parse_kr_declaration_list(ndeclaration);
5852 if (token.type != '{') {
5853 parse_error_expected("while parsing function definition", '{', NULL);
5854 eat_until_matching_token(';');
5858 assert(is_declaration(ndeclaration));
5859 type_t *type = ndeclaration->declaration.type;
5861 /* note that we don't skip typerefs: the standard doesn't allow them here
5862 * (so we can't use is_type_function here) */
5863 if (type->kind != TYPE_FUNCTION) {
5864 if (is_type_valid(type)) {
5865 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5866 type, ndeclaration->base.symbol);
5872 if (warning.aggregate_return &&
5873 is_type_compound(skip_typeref(type->function.return_type))) {
5874 warningf(HERE, "function '%Y' returns an aggregate",
5875 ndeclaration->base.symbol);
5877 if (warning.traditional && !type->function.unspecified_parameters) {
5878 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5879 ndeclaration->base.symbol);
5881 if (warning.old_style_definition && type->function.unspecified_parameters) {
5882 warningf(HERE, "old-style function definition '%Y'",
5883 ndeclaration->base.symbol);
5886 /* § 6.7.5.3 (14) a function definition with () means no
5887 * parameters (and not unspecified parameters) */
5888 if (type->function.unspecified_parameters
5889 && type->function.parameters == NULL
5890 && !type->function.kr_style_parameters) {
5891 type_t *duplicate = duplicate_type(type);
5892 duplicate->function.unspecified_parameters = false;
5894 type = typehash_insert(duplicate);
5895 if (type != duplicate) {
5896 obstack_free(type_obst, duplicate);
5898 ndeclaration->declaration.type = type;
5901 entity_t *const entity = record_entity(ndeclaration, true);
5902 assert(entity->kind == ENTITY_FUNCTION);
5903 assert(ndeclaration->kind == ENTITY_FUNCTION);
5905 function_t *function = &entity->function;
5906 if (ndeclaration != entity) {
5907 function->parameters = ndeclaration->function.parameters;
5909 assert(is_declaration(entity));
5910 type = skip_typeref(entity->declaration.type);
5912 /* push function parameters and switch scope */
5913 size_t const top = environment_top();
5914 scope_push(&function->parameters);
5916 entity_t *parameter = function->parameters.entities;
5917 for( ; parameter != NULL; parameter = parameter->base.next) {
5918 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5919 parameter->base.parent_scope = scope;
5921 assert(parameter->base.parent_scope == NULL
5922 || parameter->base.parent_scope == scope);
5923 parameter->base.parent_scope = scope;
5924 if (parameter->base.symbol == NULL) {
5925 errorf(¶meter->base.source_position, "parameter name omitted");
5928 environment_push(parameter);
5931 if (function->statement != NULL) {
5932 parser_error_multiple_definition(entity, HERE);
5935 /* parse function body */
5936 int label_stack_top = label_top();
5937 function_t *old_current_function = current_function;
5938 current_function = function;
5939 current_parent = NULL;
5941 statement_t *const body = parse_compound_statement(false);
5942 function->statement = body;
5945 check_declarations();
5946 if (warning.return_type ||
5947 warning.unreachable_code ||
5948 (warning.missing_noreturn
5949 && !(function->base.modifiers & DM_NORETURN))) {
5950 noreturn_candidate = true;
5951 check_reachable(body);
5952 if (warning.unreachable_code)
5953 walk_statements(body, check_unreachable, NULL);
5954 if (warning.missing_noreturn &&
5955 noreturn_candidate &&
5956 !(function->base.modifiers & DM_NORETURN)) {
5957 warningf(&body->base.source_position,
5958 "function '%#T' is candidate for attribute 'noreturn'",
5959 type, entity->base.symbol);
5963 assert(current_parent == NULL);
5964 assert(current_function == function);
5965 current_function = old_current_function;
5966 label_pop_to(label_stack_top);
5969 assert(scope == &function->parameters);
5971 environment_pop_to(top);
5974 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5975 source_position_t *source_position,
5976 const symbol_t *symbol)
5978 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5980 type->bitfield.base_type = base_type;
5981 type->bitfield.size_expression = size;
5984 type_t *skipped_type = skip_typeref(base_type);
5985 if (!is_type_integer(skipped_type)) {
5986 errorf(HERE, "bitfield base type '%T' is not an integer type",
5990 bit_size = skipped_type->base.size * 8;
5993 if (is_constant_expression(size)) {
5994 long v = fold_constant(size);
5997 errorf(source_position, "negative width in bit-field '%Y'",
5999 } else if (v == 0) {
6000 errorf(source_position, "zero width for bit-field '%Y'",
6002 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
6003 errorf(source_position, "width of '%Y' exceeds its type",
6006 type->bitfield.bit_size = v;
6013 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
6015 entity_t *iter = compound->members.entities;
6016 for( ; iter != NULL; iter = iter->base.next) {
6017 if (iter->kind != ENTITY_COMPOUND_MEMBER)
6020 if (iter->base.symbol == NULL) {
6021 type_t *type = skip_typeref(iter->declaration.type);
6022 if (is_type_compound(type)) {
6024 = find_compound_entry(type->compound.compound, symbol);
6031 if (iter->base.symbol == symbol) {
6039 static void parse_compound_declarators(compound_t *compound,
6040 const declaration_specifiers_t *specifiers)
6045 if (token.type == ':') {
6046 source_position_t source_position = *HERE;
6049 type_t *base_type = specifiers->type;
6050 expression_t *size = parse_constant_expression();
6052 type_t *type = make_bitfield_type(base_type, size,
6053 &source_position, sym_anonymous);
6055 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
6056 entity->base.namespc = NAMESPACE_NORMAL;
6057 entity->base.source_position = source_position;
6058 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
6059 entity->declaration.storage_class = STORAGE_CLASS_NONE;
6060 entity->declaration.modifiers = specifiers->modifiers;
6061 entity->declaration.type = type;
6063 entity = parse_declarator(specifiers,/*may_be_abstract=*/true, true);
6064 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6066 if (token.type == ':') {
6067 source_position_t source_position = *HERE;
6069 expression_t *size = parse_constant_expression();
6071 type_t *type = entity->declaration.type;
6072 type_t *bitfield_type = make_bitfield_type(type, size,
6073 &source_position, entity->base.symbol);
6074 entity->declaration.type = bitfield_type;
6078 /* make sure we don't define a symbol multiple times */
6079 symbol_t *symbol = entity->base.symbol;
6080 if (symbol != NULL) {
6081 entity_t *prev = find_compound_entry(compound, symbol);
6084 assert(prev->base.symbol == symbol);
6085 errorf(&entity->base.source_position,
6086 "multiple declarations of symbol '%Y' (declared %P)",
6087 symbol, &prev->base.source_position);
6091 append_entity(&compound->members, entity);
6093 if (token.type != ',')
6103 static void semantic_compound(compound_t *compound)
6105 entity_t *entity = compound->members.entities;
6106 for ( ; entity != NULL; entity = entity->base.next) {
6107 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
6109 type_t *orig_type = entity->declaration.type;
6110 type_t *type = skip_typeref(orig_type);
6112 if (is_type_function(type)) {
6114 "compound member '%Y' must not have function type '%T'",
6115 entity->base.symbol, orig_type);
6116 } else if (is_type_incomplete(type)) {
6117 /* §6.7.2.1 (16) flexible array member */
6118 if (is_type_array(type) && entity->base.next == NULL) {
6119 compound->has_flexible_member = true;
6122 "compound member '%Y' has incomplete type '%T'",
6123 entity->base.symbol, orig_type);
6129 static void parse_compound_type_entries(compound_t *compound)
6132 add_anchor_token('}');
6134 while (token.type != '}') {
6135 if (token.type == T_EOF) {
6136 errorf(HERE, "EOF while parsing struct");
6139 declaration_specifiers_t specifiers;
6140 memset(&specifiers, 0, sizeof(specifiers));
6141 parse_declaration_specifiers(&specifiers);
6143 parse_compound_declarators(compound, &specifiers);
6145 semantic_compound(compound);
6146 rem_anchor_token('}');
6150 static type_t *parse_typename(void)
6152 declaration_specifiers_t specifiers;
6153 memset(&specifiers, 0, sizeof(specifiers));
6154 parse_declaration_specifiers(&specifiers);
6155 if (specifiers.storage_class != STORAGE_CLASS_NONE) {
6156 /* TODO: improve error message, user does probably not know what a
6157 * storage class is...
6159 errorf(HERE, "typename may not have a storage class");
6162 type_t *result = parse_abstract_declarator(specifiers.type);
6170 typedef expression_t* (*parse_expression_function)(void);
6171 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6173 typedef struct expression_parser_function_t expression_parser_function_t;
6174 struct expression_parser_function_t {
6175 parse_expression_function parser;
6176 unsigned infix_precedence;
6177 parse_expression_infix_function infix_parser;
6180 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6183 * Prints an error message if an expression was expected but not read
6185 static expression_t *expected_expression_error(void)
6187 /* skip the error message if the error token was read */
6188 if (token.type != T_ERROR) {
6189 errorf(HERE, "expected expression, got token '%K'", &token);
6193 return create_invalid_expression();
6197 * Parse a string constant.
6199 static expression_t *parse_string_const(void)
6202 if (token.type == T_STRING_LITERAL) {
6203 string_t res = token.v.string;
6205 while (token.type == T_STRING_LITERAL) {
6206 res = concat_strings(&res, &token.v.string);
6209 if (token.type != T_WIDE_STRING_LITERAL) {
6210 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6211 /* note: that we use type_char_ptr here, which is already the
6212 * automatic converted type. revert_automatic_type_conversion
6213 * will construct the array type */
6214 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6215 cnst->string.value = res;
6219 wres = concat_string_wide_string(&res, &token.v.wide_string);
6221 wres = token.v.wide_string;
6226 switch (token.type) {
6227 case T_WIDE_STRING_LITERAL:
6228 wres = concat_wide_strings(&wres, &token.v.wide_string);
6231 case T_STRING_LITERAL:
6232 wres = concat_wide_string_string(&wres, &token.v.string);
6236 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6237 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6238 cnst->wide_string.value = wres;
6247 * Parse a boolean constant.
6249 static expression_t *parse_bool_const(bool value)
6251 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6252 cnst->base.type = type_bool;
6253 cnst->conste.v.int_value = value;
6261 * Parse an integer constant.
6263 static expression_t *parse_int_const(void)
6265 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6266 cnst->base.type = token.datatype;
6267 cnst->conste.v.int_value = token.v.intvalue;
6275 * Parse a character constant.
6277 static expression_t *parse_character_constant(void)
6279 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6280 cnst->base.type = token.datatype;
6281 cnst->conste.v.character = token.v.string;
6283 if (cnst->conste.v.character.size != 1) {
6284 if (warning.multichar && GNU_MODE) {
6285 warningf(HERE, "multi-character character constant");
6287 errorf(HERE, "more than 1 characters in character constant");
6296 * Parse a wide character constant.
6298 static expression_t *parse_wide_character_constant(void)
6300 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6301 cnst->base.type = token.datatype;
6302 cnst->conste.v.wide_character = token.v.wide_string;
6304 if (cnst->conste.v.wide_character.size != 1) {
6305 if (warning.multichar && GNU_MODE) {
6306 warningf(HERE, "multi-character character constant");
6308 errorf(HERE, "more than 1 characters in character constant");
6317 * Parse a float constant.
6319 static expression_t *parse_float_const(void)
6321 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6322 cnst->base.type = token.datatype;
6323 cnst->conste.v.float_value = token.v.floatvalue;
6330 static entity_t *create_implicit_function(symbol_t *symbol,
6331 const source_position_t *source_position)
6333 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6334 ntype->function.return_type = type_int;
6335 ntype->function.unspecified_parameters = true;
6337 type_t *type = typehash_insert(ntype);
6338 if (type != ntype) {
6342 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6343 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6344 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6345 entity->declaration.type = type;
6346 entity->declaration.implicit = true;
6347 entity->base.symbol = symbol;
6348 entity->base.source_position = *source_position;
6350 bool strict_prototypes_old = warning.strict_prototypes;
6351 warning.strict_prototypes = false;
6352 record_entity(entity, false);
6353 warning.strict_prototypes = strict_prototypes_old;
6359 * Creates a return_type (func)(argument_type) function type if not
6362 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6363 type_t *argument_type2)
6365 function_parameter_t *parameter2
6366 = obstack_alloc(type_obst, sizeof(parameter2[0]));
6367 memset(parameter2, 0, sizeof(parameter2[0]));
6368 parameter2->type = argument_type2;
6370 function_parameter_t *parameter1
6371 = obstack_alloc(type_obst, sizeof(parameter1[0]));
6372 memset(parameter1, 0, sizeof(parameter1[0]));
6373 parameter1->type = argument_type1;
6374 parameter1->next = parameter2;
6376 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6377 type->function.return_type = return_type;
6378 type->function.parameters = parameter1;
6380 type_t *result = typehash_insert(type);
6381 if (result != type) {
6389 * Creates a return_type (func)(argument_type) function type if not
6392 * @param return_type the return type
6393 * @param argument_type the argument type
6395 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6397 function_parameter_t *parameter
6398 = obstack_alloc(type_obst, sizeof(parameter[0]));
6399 memset(parameter, 0, sizeof(parameter[0]));
6400 parameter->type = argument_type;
6402 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6403 type->function.return_type = return_type;
6404 type->function.parameters = parameter;
6406 type_t *result = typehash_insert(type);
6407 if (result != type) {
6414 static type_t *make_function_0_type(type_t *return_type)
6416 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6417 type->function.return_type = return_type;
6418 type->function.parameters = NULL;
6420 type_t *result = typehash_insert(type);
6421 if (result != type) {
6429 * Creates a function type for some function like builtins.
6431 * @param symbol the symbol describing the builtin
6433 static type_t *get_builtin_symbol_type(symbol_t *symbol)
6435 switch (symbol->ID) {
6436 case T___builtin_alloca:
6437 return make_function_1_type(type_void_ptr, type_size_t);
6438 case T___builtin_huge_val:
6439 return make_function_0_type(type_double);
6440 case T___builtin_inf:
6441 return make_function_0_type(type_double);
6442 case T___builtin_inff:
6443 return make_function_0_type(type_float);
6444 case T___builtin_infl:
6445 return make_function_0_type(type_long_double);
6446 case T___builtin_nan:
6447 return make_function_1_type(type_double, type_char_ptr);
6448 case T___builtin_nanf:
6449 return make_function_1_type(type_float, type_char_ptr);
6450 case T___builtin_nanl:
6451 return make_function_1_type(type_long_double, type_char_ptr);
6452 case T___builtin_va_end:
6453 return make_function_1_type(type_void, type_valist);
6454 case T___builtin_expect:
6455 return make_function_2_type(type_long, type_long, type_long);
6457 internal_errorf(HERE, "not implemented builtin symbol found");
6462 * Performs automatic type cast as described in § 6.3.2.1.
6464 * @param orig_type the original type
6466 static type_t *automatic_type_conversion(type_t *orig_type)
6468 type_t *type = skip_typeref(orig_type);
6469 if (is_type_array(type)) {
6470 array_type_t *array_type = &type->array;
6471 type_t *element_type = array_type->element_type;
6472 unsigned qualifiers = array_type->base.qualifiers;
6474 return make_pointer_type(element_type, qualifiers);
6477 if (is_type_function(type)) {
6478 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6485 * reverts the automatic casts of array to pointer types and function
6486 * to function-pointer types as defined § 6.3.2.1
6488 type_t *revert_automatic_type_conversion(const expression_t *expression)
6490 switch (expression->kind) {
6491 case EXPR_REFERENCE: {
6492 entity_t *entity = expression->reference.entity;
6493 if (is_declaration(entity)) {
6494 return entity->declaration.type;
6495 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6496 return entity->enum_value.enum_type;
6498 panic("no declaration or enum in reference");
6503 entity_t *entity = expression->select.compound_entry;
6504 assert(is_declaration(entity));
6505 type_t *type = entity->declaration.type;
6506 return get_qualified_type(type,
6507 expression->base.type->base.qualifiers);
6510 case EXPR_UNARY_DEREFERENCE: {
6511 const expression_t *const value = expression->unary.value;
6512 type_t *const type = skip_typeref(value->base.type);
6513 assert(is_type_pointer(type));
6514 return type->pointer.points_to;
6517 case EXPR_BUILTIN_SYMBOL:
6518 return get_builtin_symbol_type(expression->builtin_symbol.symbol);
6520 case EXPR_ARRAY_ACCESS: {
6521 const expression_t *array_ref = expression->array_access.array_ref;
6522 type_t *type_left = skip_typeref(array_ref->base.type);
6523 if (!is_type_valid(type_left))
6525 assert(is_type_pointer(type_left));
6526 return type_left->pointer.points_to;
6529 case EXPR_STRING_LITERAL: {
6530 size_t size = expression->string.value.size;
6531 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6534 case EXPR_WIDE_STRING_LITERAL: {
6535 size_t size = expression->wide_string.value.size;
6536 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6539 case EXPR_COMPOUND_LITERAL:
6540 return expression->compound_literal.type;
6545 return expression->base.type;
6548 static expression_t *parse_reference(void)
6550 symbol_t *const symbol = token.v.symbol;
6552 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6554 if (entity == NULL) {
6555 if (!strict_mode && look_ahead(1)->type == '(') {
6556 /* an implicitly declared function */
6557 if (warning.implicit_function_declaration) {
6558 warningf(HERE, "implicit declaration of function '%Y'",
6562 entity = create_implicit_function(symbol, HERE);
6564 errorf(HERE, "unknown symbol '%Y' found.", symbol);
6565 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6571 if (is_declaration(entity)) {
6572 orig_type = entity->declaration.type;
6573 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6574 orig_type = entity->enum_value.enum_type;
6575 } else if (entity->kind == ENTITY_TYPEDEF) {
6576 errorf(HERE, "encountered typedef name '%Y' while parsing expression",
6579 return create_invalid_expression();
6581 panic("expected declaration or enum value in reference");
6584 /* we always do the auto-type conversions; the & and sizeof parser contains
6585 * code to revert this! */
6586 type_t *type = automatic_type_conversion(orig_type);
6588 expression_kind_t kind = EXPR_REFERENCE;
6589 if (entity->kind == ENTITY_ENUM_VALUE)
6590 kind = EXPR_REFERENCE_ENUM_VALUE;
6592 expression_t *expression = allocate_expression_zero(kind);
6593 expression->reference.entity = entity;
6594 expression->base.type = type;
6596 /* this declaration is used */
6597 if (is_declaration(entity)) {
6598 entity->declaration.used = true;
6601 if (entity->base.parent_scope != file_scope
6602 && entity->base.parent_scope->depth < current_function->parameters.depth
6603 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6604 if (entity->kind == ENTITY_VARIABLE) {
6605 /* access of a variable from an outer function */
6606 entity->variable.address_taken = true;
6608 current_function->need_closure = true;
6611 /* check for deprecated functions */
6612 if (warning.deprecated_declarations
6613 && is_declaration(entity)
6614 && entity->declaration.modifiers & DM_DEPRECATED) {
6615 declaration_t *declaration = &entity->declaration;
6617 char const *const prefix = entity->kind == ENTITY_FUNCTION ?
6618 "function" : "variable";
6620 if (declaration->deprecated_string != NULL) {
6621 warningf(HERE, "%s '%Y' is deprecated (declared %P): \"%s\"",
6622 prefix, entity->base.symbol, &entity->base.source_position,
6623 declaration->deprecated_string);
6625 warningf(HERE, "%s '%Y' is deprecated (declared %P)", prefix,
6626 entity->base.symbol, &entity->base.source_position);
6630 if (warning.init_self && entity == current_init_decl && !in_type_prop
6631 && entity->kind == ENTITY_VARIABLE) {
6632 current_init_decl = NULL;
6633 warningf(HERE, "variable '%#T' is initialized by itself",
6634 entity->declaration.type, entity->base.symbol);
6641 static bool semantic_cast(expression_t *cast)
6643 expression_t *expression = cast->unary.value;
6644 type_t *orig_dest_type = cast->base.type;
6645 type_t *orig_type_right = expression->base.type;
6646 type_t const *dst_type = skip_typeref(orig_dest_type);
6647 type_t const *src_type = skip_typeref(orig_type_right);
6648 source_position_t const *pos = &cast->base.source_position;
6650 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6651 if (dst_type == type_void)
6654 /* only integer and pointer can be casted to pointer */
6655 if (is_type_pointer(dst_type) &&
6656 !is_type_pointer(src_type) &&
6657 !is_type_integer(src_type) &&
6658 is_type_valid(src_type)) {
6659 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6663 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6664 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6668 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6669 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6673 if (warning.cast_qual &&
6674 is_type_pointer(src_type) &&
6675 is_type_pointer(dst_type)) {
6676 type_t *src = skip_typeref(src_type->pointer.points_to);
6677 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6678 unsigned missing_qualifiers =
6679 src->base.qualifiers & ~dst->base.qualifiers;
6680 if (missing_qualifiers != 0) {
6682 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6683 missing_qualifiers, orig_type_right);
6689 static expression_t *parse_compound_literal(type_t *type)
6691 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6693 parse_initializer_env_t env;
6696 env.must_be_constant = false;
6697 initializer_t *initializer = parse_initializer(&env);
6700 expression->compound_literal.initializer = initializer;
6701 expression->compound_literal.type = type;
6702 expression->base.type = automatic_type_conversion(type);
6708 * Parse a cast expression.
6710 static expression_t *parse_cast(void)
6712 add_anchor_token(')');
6714 source_position_t source_position = token.source_position;
6716 type_t *type = parse_typename();
6718 rem_anchor_token(')');
6721 if (token.type == '{') {
6722 return parse_compound_literal(type);
6725 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6726 cast->base.source_position = source_position;
6728 expression_t *value = parse_sub_expression(PREC_CAST);
6729 cast->base.type = type;
6730 cast->unary.value = value;
6732 if (! semantic_cast(cast)) {
6733 /* TODO: record the error in the AST. else it is impossible to detect it */
6738 return create_invalid_expression();
6742 * Parse a statement expression.
6744 static expression_t *parse_statement_expression(void)
6746 add_anchor_token(')');
6748 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6750 statement_t *statement = parse_compound_statement(true);
6751 expression->statement.statement = statement;
6753 /* find last statement and use its type */
6754 type_t *type = type_void;
6755 const statement_t *stmt = statement->compound.statements;
6757 while (stmt->base.next != NULL)
6758 stmt = stmt->base.next;
6760 if (stmt->kind == STATEMENT_EXPRESSION) {
6761 type = stmt->expression.expression->base.type;
6763 } else if (warning.other) {
6764 warningf(&expression->base.source_position, "empty statement expression ({})");
6766 expression->base.type = type;
6768 rem_anchor_token(')');
6776 * Parse a parenthesized expression.
6778 static expression_t *parse_parenthesized_expression(void)
6782 switch (token.type) {
6784 /* gcc extension: a statement expression */
6785 return parse_statement_expression();
6789 return parse_cast();
6791 if (is_typedef_symbol(token.v.symbol)) {
6792 return parse_cast();
6796 add_anchor_token(')');
6797 expression_t *result = parse_expression();
6798 rem_anchor_token(')');
6805 static expression_t *parse_function_keyword(void)
6809 if (current_function == NULL) {
6810 errorf(HERE, "'__func__' used outside of a function");
6813 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6814 expression->base.type = type_char_ptr;
6815 expression->funcname.kind = FUNCNAME_FUNCTION;
6822 static expression_t *parse_pretty_function_keyword(void)
6824 if (current_function == NULL) {
6825 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6828 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6829 expression->base.type = type_char_ptr;
6830 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6832 eat(T___PRETTY_FUNCTION__);
6837 static expression_t *parse_funcsig_keyword(void)
6839 if (current_function == NULL) {
6840 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6843 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6844 expression->base.type = type_char_ptr;
6845 expression->funcname.kind = FUNCNAME_FUNCSIG;
6852 static expression_t *parse_funcdname_keyword(void)
6854 if (current_function == NULL) {
6855 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6858 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6859 expression->base.type = type_char_ptr;
6860 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6862 eat(T___FUNCDNAME__);
6867 static designator_t *parse_designator(void)
6869 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6870 result->source_position = *HERE;
6872 if (token.type != T_IDENTIFIER) {
6873 parse_error_expected("while parsing member designator",
6874 T_IDENTIFIER, NULL);
6877 result->symbol = token.v.symbol;
6880 designator_t *last_designator = result;
6882 if (token.type == '.') {
6884 if (token.type != T_IDENTIFIER) {
6885 parse_error_expected("while parsing member designator",
6886 T_IDENTIFIER, NULL);
6889 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6890 designator->source_position = *HERE;
6891 designator->symbol = token.v.symbol;
6894 last_designator->next = designator;
6895 last_designator = designator;
6898 if (token.type == '[') {
6900 add_anchor_token(']');
6901 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6902 designator->source_position = *HERE;
6903 designator->array_index = parse_expression();
6904 rem_anchor_token(']');
6906 if (designator->array_index == NULL) {
6910 last_designator->next = designator;
6911 last_designator = designator;
6923 * Parse the __builtin_offsetof() expression.
6925 static expression_t *parse_offsetof(void)
6927 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6928 expression->base.type = type_size_t;
6930 eat(T___builtin_offsetof);
6933 add_anchor_token(',');
6934 type_t *type = parse_typename();
6935 rem_anchor_token(',');
6937 add_anchor_token(')');
6938 designator_t *designator = parse_designator();
6939 rem_anchor_token(')');
6942 expression->offsetofe.type = type;
6943 expression->offsetofe.designator = designator;
6946 memset(&path, 0, sizeof(path));
6947 path.top_type = type;
6948 path.path = NEW_ARR_F(type_path_entry_t, 0);
6950 descend_into_subtype(&path);
6952 if (!walk_designator(&path, designator, true)) {
6953 return create_invalid_expression();
6956 DEL_ARR_F(path.path);
6960 return create_invalid_expression();
6964 * Parses a _builtin_va_start() expression.
6966 static expression_t *parse_va_start(void)
6968 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6970 eat(T___builtin_va_start);
6973 add_anchor_token(',');
6974 expression->va_starte.ap = parse_assignment_expression();
6975 rem_anchor_token(',');
6977 expression_t *const expr = parse_assignment_expression();
6978 if (expr->kind == EXPR_REFERENCE) {
6979 entity_t *const entity = expr->reference.entity;
6980 if (entity->base.parent_scope != ¤t_function->parameters
6981 || entity->base.next != NULL
6982 || entity->kind != ENTITY_VARIABLE) {
6983 errorf(&expr->base.source_position,
6984 "second argument of 'va_start' must be last parameter of the current function");
6986 expression->va_starte.parameter = &entity->variable;
6993 return create_invalid_expression();
6997 * Parses a _builtin_va_arg() expression.
6999 static expression_t *parse_va_arg(void)
7001 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
7003 eat(T___builtin_va_arg);
7006 expression->va_arge.ap = parse_assignment_expression();
7008 expression->base.type = parse_typename();
7013 return create_invalid_expression();
7016 static expression_t *parse_builtin_symbol(void)
7018 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_SYMBOL);
7020 symbol_t *symbol = token.v.symbol;
7022 expression->builtin_symbol.symbol = symbol;
7025 type_t *type = get_builtin_symbol_type(symbol);
7026 type = automatic_type_conversion(type);
7028 expression->base.type = type;
7033 * Parses a __builtin_constant() expression.
7035 static expression_t *parse_builtin_constant(void)
7037 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7039 eat(T___builtin_constant_p);
7042 add_anchor_token(')');
7043 expression->builtin_constant.value = parse_assignment_expression();
7044 rem_anchor_token(')');
7046 expression->base.type = type_int;
7050 return create_invalid_expression();
7054 * Parses a __builtin_prefetch() expression.
7056 static expression_t *parse_builtin_prefetch(void)
7058 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_PREFETCH);
7060 eat(T___builtin_prefetch);
7063 add_anchor_token(')');
7064 expression->builtin_prefetch.adr = parse_assignment_expression();
7065 if (token.type == ',') {
7067 expression->builtin_prefetch.rw = parse_assignment_expression();
7069 if (token.type == ',') {
7071 expression->builtin_prefetch.locality = parse_assignment_expression();
7073 rem_anchor_token(')');
7075 expression->base.type = type_void;
7079 return create_invalid_expression();
7083 * Parses a __builtin_is_*() compare expression.
7085 static expression_t *parse_compare_builtin(void)
7087 expression_t *expression;
7089 switch (token.type) {
7090 case T___builtin_isgreater:
7091 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7093 case T___builtin_isgreaterequal:
7094 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7096 case T___builtin_isless:
7097 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7099 case T___builtin_islessequal:
7100 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7102 case T___builtin_islessgreater:
7103 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7105 case T___builtin_isunordered:
7106 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7109 internal_errorf(HERE, "invalid compare builtin found");
7111 expression->base.source_position = *HERE;
7115 expression->binary.left = parse_assignment_expression();
7117 expression->binary.right = parse_assignment_expression();
7120 type_t *const orig_type_left = expression->binary.left->base.type;
7121 type_t *const orig_type_right = expression->binary.right->base.type;
7123 type_t *const type_left = skip_typeref(orig_type_left);
7124 type_t *const type_right = skip_typeref(orig_type_right);
7125 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7126 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7127 type_error_incompatible("invalid operands in comparison",
7128 &expression->base.source_position, orig_type_left, orig_type_right);
7131 semantic_comparison(&expression->binary);
7136 return create_invalid_expression();
7141 * Parses a __builtin_expect() expression.
7143 static expression_t *parse_builtin_expect(void)
7145 expression_t *expression
7146 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7148 eat(T___builtin_expect);
7151 expression->binary.left = parse_assignment_expression();
7153 expression->binary.right = parse_constant_expression();
7156 expression->base.type = expression->binary.left->base.type;
7160 return create_invalid_expression();
7165 * Parses a MS assume() expression.
7167 static expression_t *parse_assume(void)
7169 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7174 add_anchor_token(')');
7175 expression->unary.value = parse_assignment_expression();
7176 rem_anchor_token(')');
7179 expression->base.type = type_void;
7182 return create_invalid_expression();
7186 * Return the declaration for a given label symbol or create a new one.
7188 * @param symbol the symbol of the label
7190 static label_t *get_label(symbol_t *symbol)
7193 assert(current_function != NULL);
7195 label = get_entity(symbol, NAMESPACE_LABEL);
7196 /* if we found a local label, we already created the declaration */
7197 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7198 if (label->base.parent_scope != scope) {
7199 assert(label->base.parent_scope->depth < scope->depth);
7200 current_function->goto_to_outer = true;
7202 return &label->label;
7205 label = get_entity(symbol, NAMESPACE_LABEL);
7206 /* if we found a label in the same function, then we already created the
7209 && label->base.parent_scope == ¤t_function->parameters) {
7210 return &label->label;
7213 /* otherwise we need to create a new one */
7214 label = allocate_entity_zero(ENTITY_LABEL);
7215 label->base.namespc = NAMESPACE_LABEL;
7216 label->base.symbol = symbol;
7220 return &label->label;
7224 * Parses a GNU && label address expression.
7226 static expression_t *parse_label_address(void)
7228 source_position_t source_position = token.source_position;
7230 if (token.type != T_IDENTIFIER) {
7231 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7234 symbol_t *symbol = token.v.symbol;
7237 label_t *label = get_label(symbol);
7239 label->address_taken = true;
7241 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7242 expression->base.source_position = source_position;
7244 /* label address is threaten as a void pointer */
7245 expression->base.type = type_void_ptr;
7246 expression->label_address.label = label;
7249 return create_invalid_expression();
7253 * Parse a microsoft __noop expression.
7255 static expression_t *parse_noop_expression(void)
7257 /* the result is a (int)0 */
7258 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7259 cnst->base.type = type_int;
7260 cnst->conste.v.int_value = 0;
7261 cnst->conste.is_ms_noop = true;
7265 if (token.type == '(') {
7266 /* parse arguments */
7268 add_anchor_token(')');
7269 add_anchor_token(',');
7271 if (token.type != ')') {
7273 (void)parse_assignment_expression();
7274 if (token.type != ',')
7280 rem_anchor_token(',');
7281 rem_anchor_token(')');
7289 * Parses a primary expression.
7291 static expression_t *parse_primary_expression(void)
7293 switch (token.type) {
7294 case T_false: return parse_bool_const(false);
7295 case T_true: return parse_bool_const(true);
7296 case T_INTEGER: return parse_int_const();
7297 case T_CHARACTER_CONSTANT: return parse_character_constant();
7298 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7299 case T_FLOATINGPOINT: return parse_float_const();
7300 case T_STRING_LITERAL:
7301 case T_WIDE_STRING_LITERAL: return parse_string_const();
7302 case T_IDENTIFIER: return parse_reference();
7303 case T___FUNCTION__:
7304 case T___func__: return parse_function_keyword();
7305 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7306 case T___FUNCSIG__: return parse_funcsig_keyword();
7307 case T___FUNCDNAME__: return parse_funcdname_keyword();
7308 case T___builtin_offsetof: return parse_offsetof();
7309 case T___builtin_va_start: return parse_va_start();
7310 case T___builtin_va_arg: return parse_va_arg();
7311 case T___builtin_expect:
7312 case T___builtin_alloca:
7313 case T___builtin_inf:
7314 case T___builtin_inff:
7315 case T___builtin_infl:
7316 case T___builtin_nan:
7317 case T___builtin_nanf:
7318 case T___builtin_nanl:
7319 case T___builtin_huge_val:
7320 case T___builtin_va_end: return parse_builtin_symbol();
7321 case T___builtin_isgreater:
7322 case T___builtin_isgreaterequal:
7323 case T___builtin_isless:
7324 case T___builtin_islessequal:
7325 case T___builtin_islessgreater:
7326 case T___builtin_isunordered: return parse_compare_builtin();
7327 case T___builtin_constant_p: return parse_builtin_constant();
7328 case T___builtin_prefetch: return parse_builtin_prefetch();
7329 case T__assume: return parse_assume();
7332 return parse_label_address();
7335 case '(': return parse_parenthesized_expression();
7336 case T___noop: return parse_noop_expression();
7339 errorf(HERE, "unexpected token %K, expected an expression", &token);
7340 return create_invalid_expression();
7344 * Check if the expression has the character type and issue a warning then.
7346 static void check_for_char_index_type(const expression_t *expression)
7348 type_t *const type = expression->base.type;
7349 const type_t *const base_type = skip_typeref(type);
7351 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7352 warning.char_subscripts) {
7353 warningf(&expression->base.source_position,
7354 "array subscript has type '%T'", type);
7358 static expression_t *parse_array_expression(expression_t *left)
7360 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7363 add_anchor_token(']');
7365 expression_t *inside = parse_expression();
7367 type_t *const orig_type_left = left->base.type;
7368 type_t *const orig_type_inside = inside->base.type;
7370 type_t *const type_left = skip_typeref(orig_type_left);
7371 type_t *const type_inside = skip_typeref(orig_type_inside);
7373 type_t *return_type;
7374 array_access_expression_t *array_access = &expression->array_access;
7375 if (is_type_pointer(type_left)) {
7376 return_type = type_left->pointer.points_to;
7377 array_access->array_ref = left;
7378 array_access->index = inside;
7379 check_for_char_index_type(inside);
7380 } else if (is_type_pointer(type_inside)) {
7381 return_type = type_inside->pointer.points_to;
7382 array_access->array_ref = inside;
7383 array_access->index = left;
7384 array_access->flipped = true;
7385 check_for_char_index_type(left);
7387 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7389 "array access on object with non-pointer types '%T', '%T'",
7390 orig_type_left, orig_type_inside);
7392 return_type = type_error_type;
7393 array_access->array_ref = left;
7394 array_access->index = inside;
7397 expression->base.type = automatic_type_conversion(return_type);
7399 rem_anchor_token(']');
7405 static expression_t *parse_typeprop(expression_kind_t const kind)
7407 expression_t *tp_expression = allocate_expression_zero(kind);
7408 tp_expression->base.type = type_size_t;
7410 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7412 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7414 /* we only refer to a type property, mark this case */
7415 bool old = in_type_prop;
7416 in_type_prop = true;
7419 expression_t *expression;
7420 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7422 add_anchor_token(')');
7423 orig_type = parse_typename();
7424 rem_anchor_token(')');
7427 if (token.type == '{') {
7428 /* It was not sizeof(type) after all. It is sizeof of an expression
7429 * starting with a compound literal */
7430 expression = parse_compound_literal(orig_type);
7431 goto typeprop_expression;
7434 expression = parse_sub_expression(PREC_UNARY);
7436 typeprop_expression:
7437 tp_expression->typeprop.tp_expression = expression;
7439 orig_type = revert_automatic_type_conversion(expression);
7440 expression->base.type = orig_type;
7443 tp_expression->typeprop.type = orig_type;
7444 type_t const* const type = skip_typeref(orig_type);
7445 char const* const wrong_type =
7446 is_type_incomplete(type) ? "incomplete" :
7447 type->kind == TYPE_FUNCTION ? "function designator" :
7448 type->kind == TYPE_BITFIELD ? "bitfield" :
7450 if (wrong_type != NULL) {
7451 errorf(&tp_expression->base.source_position,
7452 "operand of %s expression must not be of %s type '%T'",
7453 what, wrong_type, orig_type);
7458 return tp_expression;
7461 static expression_t *parse_sizeof(void)
7463 return parse_typeprop(EXPR_SIZEOF);
7466 static expression_t *parse_alignof(void)
7468 return parse_typeprop(EXPR_ALIGNOF);
7471 static expression_t *parse_select_expression(expression_t *compound)
7473 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7474 select->select.compound = compound;
7476 assert(token.type == '.' || token.type == T_MINUSGREATER);
7477 bool is_pointer = (token.type == T_MINUSGREATER);
7480 if (token.type != T_IDENTIFIER) {
7481 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7484 symbol_t *symbol = token.v.symbol;
7487 type_t *const orig_type = compound->base.type;
7488 type_t *const type = skip_typeref(orig_type);
7491 bool saw_error = false;
7492 if (is_type_pointer(type)) {
7495 "request for member '%Y' in something not a struct or union, but '%T'",
7499 type_left = skip_typeref(type->pointer.points_to);
7501 if (is_pointer && is_type_valid(type)) {
7502 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7509 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7510 type_left->kind == TYPE_COMPOUND_UNION) {
7511 compound_t *compound = type_left->compound.compound;
7513 if (!compound->complete) {
7514 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7516 goto create_error_entry;
7519 entry = find_compound_entry(compound, symbol);
7520 if (entry == NULL) {
7521 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7522 goto create_error_entry;
7525 if (is_type_valid(type_left) && !saw_error) {
7527 "request for member '%Y' in something not a struct or union, but '%T'",
7531 return create_invalid_expression();
7534 assert(is_declaration(entry));
7535 select->select.compound_entry = entry;
7537 type_t *entry_type = entry->declaration.type;
7539 = get_qualified_type(entry_type, type_left->base.qualifiers);
7541 /* we always do the auto-type conversions; the & and sizeof parser contains
7542 * code to revert this! */
7543 select->base.type = automatic_type_conversion(res_type);
7545 type_t *skipped = skip_typeref(res_type);
7546 if (skipped->kind == TYPE_BITFIELD) {
7547 select->base.type = skipped->bitfield.base_type;
7553 static void check_call_argument(const function_parameter_t *parameter,
7554 call_argument_t *argument, unsigned pos)
7556 type_t *expected_type = parameter->type;
7557 type_t *expected_type_skip = skip_typeref(expected_type);
7558 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7559 expression_t *arg_expr = argument->expression;
7560 type_t *arg_type = skip_typeref(arg_expr->base.type);
7562 /* handle transparent union gnu extension */
7563 if (is_type_union(expected_type_skip)
7564 && (expected_type_skip->base.modifiers
7565 & TYPE_MODIFIER_TRANSPARENT_UNION)) {
7566 compound_t *union_decl = expected_type_skip->compound.compound;
7567 type_t *best_type = NULL;
7568 entity_t *entry = union_decl->members.entities;
7569 for ( ; entry != NULL; entry = entry->base.next) {
7570 assert(is_declaration(entry));
7571 type_t *decl_type = entry->declaration.type;
7572 error = semantic_assign(decl_type, arg_expr);
7573 if (error == ASSIGN_ERROR_INCOMPATIBLE
7574 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7577 if (error == ASSIGN_SUCCESS) {
7578 best_type = decl_type;
7579 } else if (best_type == NULL) {
7580 best_type = decl_type;
7584 if (best_type != NULL) {
7585 expected_type = best_type;
7589 error = semantic_assign(expected_type, arg_expr);
7590 argument->expression = create_implicit_cast(argument->expression,
7593 if (error != ASSIGN_SUCCESS) {
7594 /* report exact scope in error messages (like "in argument 3") */
7596 snprintf(buf, sizeof(buf), "call argument %u", pos);
7597 report_assign_error(error, expected_type, arg_expr, buf,
7598 &arg_expr->base.source_position);
7599 } else if (warning.traditional || warning.conversion) {
7600 type_t *const promoted_type = get_default_promoted_type(arg_type);
7601 if (!types_compatible(expected_type_skip, promoted_type) &&
7602 !types_compatible(expected_type_skip, type_void_ptr) &&
7603 !types_compatible(type_void_ptr, promoted_type)) {
7604 /* Deliberately show the skipped types in this warning */
7605 warningf(&arg_expr->base.source_position,
7606 "passing call argument %u as '%T' rather than '%T' due to prototype",
7607 pos, expected_type_skip, promoted_type);
7613 * Parse a call expression, ie. expression '( ... )'.
7615 * @param expression the function address
7617 static expression_t *parse_call_expression(expression_t *expression)
7619 expression_t *result = allocate_expression_zero(EXPR_CALL);
7620 call_expression_t *call = &result->call;
7621 call->function = expression;
7623 type_t *const orig_type = expression->base.type;
7624 type_t *const type = skip_typeref(orig_type);
7626 function_type_t *function_type = NULL;
7627 if (is_type_pointer(type)) {
7628 type_t *const to_type = skip_typeref(type->pointer.points_to);
7630 if (is_type_function(to_type)) {
7631 function_type = &to_type->function;
7632 call->base.type = function_type->return_type;
7636 if (function_type == NULL && is_type_valid(type)) {
7637 errorf(HERE, "called object '%E' (type '%T') is not a pointer to a function", expression, orig_type);
7640 /* parse arguments */
7642 add_anchor_token(')');
7643 add_anchor_token(',');
7645 if (token.type != ')') {
7646 call_argument_t *last_argument = NULL;
7649 call_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
7651 argument->expression = parse_assignment_expression();
7652 if (last_argument == NULL) {
7653 call->arguments = argument;
7655 last_argument->next = argument;
7657 last_argument = argument;
7659 if (token.type != ',')
7664 rem_anchor_token(',');
7665 rem_anchor_token(')');
7668 if (function_type == NULL)
7671 function_parameter_t *parameter = function_type->parameters;
7672 call_argument_t *argument = call->arguments;
7673 if (!function_type->unspecified_parameters) {
7674 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7675 parameter = parameter->next, argument = argument->next) {
7676 check_call_argument(parameter, argument, ++pos);
7679 if (parameter != NULL) {
7680 errorf(HERE, "too few arguments to function '%E'", expression);
7681 } else if (argument != NULL && !function_type->variadic) {
7682 errorf(HERE, "too many arguments to function '%E'", expression);
7686 /* do default promotion */
7687 for( ; argument != NULL; argument = argument->next) {
7688 type_t *type = argument->expression->base.type;
7690 type = get_default_promoted_type(type);
7692 argument->expression
7693 = create_implicit_cast(argument->expression, type);
7696 check_format(&result->call);
7698 if (warning.aggregate_return &&
7699 is_type_compound(skip_typeref(function_type->return_type))) {
7700 warningf(&result->base.source_position,
7701 "function call has aggregate value");
7708 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7710 static bool same_compound_type(const type_t *type1, const type_t *type2)
7713 is_type_compound(type1) &&
7714 type1->kind == type2->kind &&
7715 type1->compound.compound == type2->compound.compound;
7719 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7721 * @param expression the conditional expression
7723 static expression_t *parse_conditional_expression(expression_t *expression)
7725 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7727 conditional_expression_t *conditional = &result->conditional;
7728 conditional->condition = expression;
7731 add_anchor_token(':');
7734 type_t *const condition_type_orig = expression->base.type;
7735 type_t *const condition_type = skip_typeref(condition_type_orig);
7736 if (!is_type_scalar(condition_type) && is_type_valid(condition_type)) {
7737 type_error("expected a scalar type in conditional condition",
7738 &expression->base.source_position, condition_type_orig);
7741 expression_t *true_expression = expression;
7742 bool gnu_cond = false;
7743 if (GNU_MODE && token.type == ':') {
7746 true_expression = parse_expression();
7748 rem_anchor_token(':');
7750 expression_t *false_expression =
7751 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7753 type_t *const orig_true_type = true_expression->base.type;
7754 type_t *const orig_false_type = false_expression->base.type;
7755 type_t *const true_type = skip_typeref(orig_true_type);
7756 type_t *const false_type = skip_typeref(orig_false_type);
7759 type_t *result_type;
7760 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7761 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7762 /* ISO/IEC 14882:1998(E) §5.16:2 */
7763 if (true_expression->kind == EXPR_UNARY_THROW) {
7764 result_type = false_type;
7765 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7766 result_type = true_type;
7768 if (warning.other && (
7769 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7770 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7772 warningf(&conditional->base.source_position,
7773 "ISO C forbids conditional expression with only one void side");
7775 result_type = type_void;
7777 } else if (is_type_arithmetic(true_type)
7778 && is_type_arithmetic(false_type)) {
7779 result_type = semantic_arithmetic(true_type, false_type);
7781 true_expression = create_implicit_cast(true_expression, result_type);
7782 false_expression = create_implicit_cast(false_expression, result_type);
7784 conditional->true_expression = true_expression;
7785 conditional->false_expression = false_expression;
7786 conditional->base.type = result_type;
7787 } else if (same_compound_type(true_type, false_type)) {
7788 /* just take 1 of the 2 types */
7789 result_type = true_type;
7790 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7791 type_t *pointer_type;
7793 expression_t *other_expression;
7794 if (is_type_pointer(true_type) &&
7795 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7796 pointer_type = true_type;
7797 other_type = false_type;
7798 other_expression = false_expression;
7800 pointer_type = false_type;
7801 other_type = true_type;
7802 other_expression = true_expression;
7805 if (is_null_pointer_constant(other_expression)) {
7806 result_type = pointer_type;
7807 } else if (is_type_pointer(other_type)) {
7808 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7809 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7812 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7813 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7815 } else if (types_compatible(get_unqualified_type(to1),
7816 get_unqualified_type(to2))) {
7819 if (warning.other) {
7820 warningf(&conditional->base.source_position,
7821 "pointer types '%T' and '%T' in conditional expression are incompatible",
7822 true_type, false_type);
7827 type_t *const type =
7828 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7829 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7830 } else if (is_type_integer(other_type)) {
7831 if (warning.other) {
7832 warningf(&conditional->base.source_position,
7833 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7835 result_type = pointer_type;
7837 if (is_type_valid(other_type)) {
7838 type_error_incompatible("while parsing conditional",
7839 &expression->base.source_position, true_type, false_type);
7841 result_type = type_error_type;
7844 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7845 type_error_incompatible("while parsing conditional",
7846 &conditional->base.source_position, true_type,
7849 result_type = type_error_type;
7852 conditional->true_expression
7853 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7854 conditional->false_expression
7855 = create_implicit_cast(false_expression, result_type);
7856 conditional->base.type = result_type;
7859 return create_invalid_expression();
7863 * Parse an extension expression.
7865 static expression_t *parse_extension(void)
7867 eat(T___extension__);
7869 bool old_gcc_extension = in_gcc_extension;
7870 in_gcc_extension = true;
7871 expression_t *expression = parse_sub_expression(PREC_UNARY);
7872 in_gcc_extension = old_gcc_extension;
7877 * Parse a __builtin_classify_type() expression.
7879 static expression_t *parse_builtin_classify_type(void)
7881 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7882 result->base.type = type_int;
7884 eat(T___builtin_classify_type);
7887 add_anchor_token(')');
7888 expression_t *expression = parse_expression();
7889 rem_anchor_token(')');
7891 result->classify_type.type_expression = expression;
7895 return create_invalid_expression();
7899 * Parse a delete expression
7900 * ISO/IEC 14882:1998(E) §5.3.5
7902 static expression_t *parse_delete(void)
7904 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7905 result->base.type = type_void;
7909 if (token.type == '[') {
7911 result->kind = EXPR_UNARY_DELETE_ARRAY;
7916 expression_t *const value = parse_sub_expression(PREC_CAST);
7917 result->unary.value = value;
7919 type_t *const type = skip_typeref(value->base.type);
7920 if (!is_type_pointer(type)) {
7921 errorf(&value->base.source_position,
7922 "operand of delete must have pointer type");
7923 } else if (warning.other &&
7924 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7925 warningf(&value->base.source_position,
7926 "deleting 'void*' is undefined");
7933 * Parse a throw expression
7934 * ISO/IEC 14882:1998(E) §15:1
7936 static expression_t *parse_throw(void)
7938 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7939 result->base.type = type_void;
7943 expression_t *value = NULL;
7944 switch (token.type) {
7946 value = parse_assignment_expression();
7947 /* ISO/IEC 14882:1998(E) §15.1:3 */
7948 type_t *const orig_type = value->base.type;
7949 type_t *const type = skip_typeref(orig_type);
7950 if (is_type_incomplete(type)) {
7951 errorf(&value->base.source_position,
7952 "cannot throw object of incomplete type '%T'", orig_type);
7953 } else if (is_type_pointer(type)) {
7954 type_t *const points_to = skip_typeref(type->pointer.points_to);
7955 if (is_type_incomplete(points_to) &&
7956 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7957 errorf(&value->base.source_position,
7958 "cannot throw pointer to incomplete type '%T'", orig_type);
7966 result->unary.value = value;
7971 static bool check_pointer_arithmetic(const source_position_t *source_position,
7972 type_t *pointer_type,
7973 type_t *orig_pointer_type)
7975 type_t *points_to = pointer_type->pointer.points_to;
7976 points_to = skip_typeref(points_to);
7978 if (is_type_incomplete(points_to)) {
7979 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7980 errorf(source_position,
7981 "arithmetic with pointer to incomplete type '%T' not allowed",
7984 } else if (warning.pointer_arith) {
7985 warningf(source_position,
7986 "pointer of type '%T' used in arithmetic",
7989 } else if (is_type_function(points_to)) {
7991 errorf(source_position,
7992 "arithmetic with pointer to function type '%T' not allowed",
7995 } else if (warning.pointer_arith) {
7996 warningf(source_position,
7997 "pointer to a function '%T' used in arithmetic",
8004 static bool is_lvalue(const expression_t *expression)
8006 /* TODO: doesn't seem to be consistent with §6.3.2.1 (1) */
8007 switch (expression->kind) {
8008 case EXPR_REFERENCE:
8009 case EXPR_ARRAY_ACCESS:
8011 case EXPR_UNARY_DEREFERENCE:
8015 /* Claim it is an lvalue, if the type is invalid. There was a parse
8016 * error before, which maybe prevented properly recognizing it as
8018 return !is_type_valid(skip_typeref(expression->base.type));
8022 static void semantic_incdec(unary_expression_t *expression)
8024 type_t *const orig_type = expression->value->base.type;
8025 type_t *const type = skip_typeref(orig_type);
8026 if (is_type_pointer(type)) {
8027 if (!check_pointer_arithmetic(&expression->base.source_position,
8031 } else if (!is_type_real(type) && is_type_valid(type)) {
8032 /* TODO: improve error message */
8033 errorf(&expression->base.source_position,
8034 "operation needs an arithmetic or pointer type");
8037 if (!is_lvalue(expression->value)) {
8038 /* TODO: improve error message */
8039 errorf(&expression->base.source_position, "lvalue required as operand");
8041 expression->base.type = orig_type;
8044 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8046 type_t *const orig_type = expression->value->base.type;
8047 type_t *const type = skip_typeref(orig_type);
8048 if (!is_type_arithmetic(type)) {
8049 if (is_type_valid(type)) {
8050 /* TODO: improve error message */
8051 errorf(&expression->base.source_position,
8052 "operation needs an arithmetic type");
8057 expression->base.type = orig_type;
8060 static void semantic_unexpr_plus(unary_expression_t *expression)
8062 semantic_unexpr_arithmetic(expression);
8063 if (warning.traditional)
8064 warningf(&expression->base.source_position,
8065 "traditional C rejects the unary plus operator");
8068 static expression_t const *get_reference_address(expression_t const *expr)
8070 bool regular_take_address = true;
8072 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8073 expr = expr->unary.value;
8075 regular_take_address = false;
8078 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8081 expr = expr->unary.value;
8084 /* special case for functions which are automatically converted to a
8085 * pointer to function without an extra TAKE_ADDRESS operation */
8086 if (!regular_take_address && expr->kind == EXPR_REFERENCE
8087 && expr->reference.entity->kind == ENTITY_FUNCTION) {
8094 static void warn_function_address_as_bool(expression_t const* expr)
8096 if (!warning.address)
8099 expr = get_reference_address(expr);
8101 warningf(&expr->base.source_position,
8102 "the address of '%Y' will always evaluate as 'true'",
8103 expr->reference.entity->base.symbol);
8107 static void semantic_not(unary_expression_t *expression)
8109 type_t *const orig_type = expression->value->base.type;
8110 type_t *const type = skip_typeref(orig_type);
8111 if (!is_type_scalar(type) && is_type_valid(type)) {
8112 errorf(&expression->base.source_position,
8113 "operand of ! must be of scalar type");
8116 warn_function_address_as_bool(expression->value);
8118 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8121 static void semantic_unexpr_integer(unary_expression_t *expression)
8123 type_t *const orig_type = expression->value->base.type;
8124 type_t *const type = skip_typeref(orig_type);
8125 if (!is_type_integer(type)) {
8126 if (is_type_valid(type)) {
8127 errorf(&expression->base.source_position,
8128 "operand of ~ must be of integer type");
8133 expression->base.type = orig_type;
8136 static void semantic_dereference(unary_expression_t *expression)
8138 type_t *const orig_type = expression->value->base.type;
8139 type_t *const type = skip_typeref(orig_type);
8140 if (!is_type_pointer(type)) {
8141 if (is_type_valid(type)) {
8142 errorf(&expression->base.source_position,
8143 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8148 type_t *result_type = type->pointer.points_to;
8149 result_type = automatic_type_conversion(result_type);
8150 expression->base.type = result_type;
8154 * Record that an address is taken (expression represents an lvalue).
8156 * @param expression the expression
8157 * @param may_be_register if true, the expression might be an register
8159 static void set_address_taken(expression_t *expression, bool may_be_register)
8161 if (expression->kind != EXPR_REFERENCE)
8164 entity_t *const entity = expression->reference.entity;
8166 if (entity->kind != ENTITY_VARIABLE)
8169 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8170 && !may_be_register) {
8171 errorf(&expression->base.source_position,
8172 "address of register variable '%Y' requested",
8173 entity->base.symbol);
8176 entity->variable.address_taken = true;
8180 * Check the semantic of the address taken expression.
8182 static void semantic_take_addr(unary_expression_t *expression)
8184 expression_t *value = expression->value;
8185 value->base.type = revert_automatic_type_conversion(value);
8187 type_t *orig_type = value->base.type;
8188 type_t *type = skip_typeref(orig_type);
8189 if (!is_type_valid(type))
8193 if (value->kind != EXPR_ARRAY_ACCESS
8194 && value->kind != EXPR_UNARY_DEREFERENCE
8195 && !is_lvalue(value)) {
8196 errorf(&expression->base.source_position,
8197 "'&' requires an lvalue");
8199 if (type->kind == TYPE_BITFIELD) {
8200 errorf(&expression->base.source_position,
8201 "'&' not allowed on object with bitfield type '%T'",
8205 set_address_taken(value, false);
8207 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8210 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8211 static expression_t *parse_##unexpression_type(void) \
8213 expression_t *unary_expression \
8214 = allocate_expression_zero(unexpression_type); \
8216 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8218 sfunc(&unary_expression->unary); \
8220 return unary_expression; \
8223 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8224 semantic_unexpr_arithmetic)
8225 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8226 semantic_unexpr_plus)
8227 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8229 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8230 semantic_dereference)
8231 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8233 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8234 semantic_unexpr_integer)
8235 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8237 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8240 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8242 static expression_t *parse_##unexpression_type(expression_t *left) \
8244 expression_t *unary_expression \
8245 = allocate_expression_zero(unexpression_type); \
8247 unary_expression->unary.value = left; \
8249 sfunc(&unary_expression->unary); \
8251 return unary_expression; \
8254 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8255 EXPR_UNARY_POSTFIX_INCREMENT,
8257 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8258 EXPR_UNARY_POSTFIX_DECREMENT,
8261 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8263 /* TODO: handle complex + imaginary types */
8265 type_left = get_unqualified_type(type_left);
8266 type_right = get_unqualified_type(type_right);
8268 /* § 6.3.1.8 Usual arithmetic conversions */
8269 if (type_left == type_long_double || type_right == type_long_double) {
8270 return type_long_double;
8271 } else if (type_left == type_double || type_right == type_double) {
8273 } else if (type_left == type_float || type_right == type_float) {
8277 type_left = promote_integer(type_left);
8278 type_right = promote_integer(type_right);
8280 if (type_left == type_right)
8283 bool const signed_left = is_type_signed(type_left);
8284 bool const signed_right = is_type_signed(type_right);
8285 int const rank_left = get_rank(type_left);
8286 int const rank_right = get_rank(type_right);
8288 if (signed_left == signed_right)
8289 return rank_left >= rank_right ? type_left : type_right;
8298 u_rank = rank_right;
8299 u_type = type_right;
8301 s_rank = rank_right;
8302 s_type = type_right;
8307 if (u_rank >= s_rank)
8310 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8312 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8313 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8317 case ATOMIC_TYPE_INT: return type_unsigned_int;
8318 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8319 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8321 default: panic("invalid atomic type");
8326 * Check the semantic restrictions for a binary expression.
8328 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8330 expression_t *const left = expression->left;
8331 expression_t *const right = expression->right;
8332 type_t *const orig_type_left = left->base.type;
8333 type_t *const orig_type_right = right->base.type;
8334 type_t *const type_left = skip_typeref(orig_type_left);
8335 type_t *const type_right = skip_typeref(orig_type_right);
8337 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8338 /* TODO: improve error message */
8339 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8340 errorf(&expression->base.source_position,
8341 "operation needs arithmetic types");
8346 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8347 expression->left = create_implicit_cast(left, arithmetic_type);
8348 expression->right = create_implicit_cast(right, arithmetic_type);
8349 expression->base.type = arithmetic_type;
8352 static void warn_div_by_zero(binary_expression_t const *const expression)
8354 if (!warning.div_by_zero ||
8355 !is_type_integer(expression->base.type))
8358 expression_t const *const right = expression->right;
8359 /* The type of the right operand can be different for /= */
8360 if (is_type_integer(right->base.type) &&
8361 is_constant_expression(right) &&
8362 fold_constant(right) == 0) {
8363 warningf(&expression->base.source_position, "division by zero");
8368 * Check the semantic restrictions for a div/mod expression.
8370 static void semantic_divmod_arithmetic(binary_expression_t *expression) {
8371 semantic_binexpr_arithmetic(expression);
8372 warn_div_by_zero(expression);
8375 static void semantic_shift_op(binary_expression_t *expression)
8377 expression_t *const left = expression->left;
8378 expression_t *const right = expression->right;
8379 type_t *const orig_type_left = left->base.type;
8380 type_t *const orig_type_right = right->base.type;
8381 type_t * type_left = skip_typeref(orig_type_left);
8382 type_t * type_right = skip_typeref(orig_type_right);
8384 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8385 /* TODO: improve error message */
8386 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8387 errorf(&expression->base.source_position,
8388 "operands of shift operation must have integer types");
8393 type_left = promote_integer(type_left);
8394 type_right = promote_integer(type_right);
8396 expression->left = create_implicit_cast(left, type_left);
8397 expression->right = create_implicit_cast(right, type_right);
8398 expression->base.type = type_left;
8401 static void semantic_add(binary_expression_t *expression)
8403 expression_t *const left = expression->left;
8404 expression_t *const right = expression->right;
8405 type_t *const orig_type_left = left->base.type;
8406 type_t *const orig_type_right = right->base.type;
8407 type_t *const type_left = skip_typeref(orig_type_left);
8408 type_t *const type_right = skip_typeref(orig_type_right);
8411 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8412 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8413 expression->left = create_implicit_cast(left, arithmetic_type);
8414 expression->right = create_implicit_cast(right, arithmetic_type);
8415 expression->base.type = arithmetic_type;
8417 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8418 check_pointer_arithmetic(&expression->base.source_position,
8419 type_left, orig_type_left);
8420 expression->base.type = type_left;
8421 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8422 check_pointer_arithmetic(&expression->base.source_position,
8423 type_right, orig_type_right);
8424 expression->base.type = type_right;
8425 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8426 errorf(&expression->base.source_position,
8427 "invalid operands to binary + ('%T', '%T')",
8428 orig_type_left, orig_type_right);
8432 static void semantic_sub(binary_expression_t *expression)
8434 expression_t *const left = expression->left;
8435 expression_t *const right = expression->right;
8436 type_t *const orig_type_left = left->base.type;
8437 type_t *const orig_type_right = right->base.type;
8438 type_t *const type_left = skip_typeref(orig_type_left);
8439 type_t *const type_right = skip_typeref(orig_type_right);
8440 source_position_t const *const pos = &expression->base.source_position;
8443 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8444 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8445 expression->left = create_implicit_cast(left, arithmetic_type);
8446 expression->right = create_implicit_cast(right, arithmetic_type);
8447 expression->base.type = arithmetic_type;
8449 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8450 check_pointer_arithmetic(&expression->base.source_position,
8451 type_left, orig_type_left);
8452 expression->base.type = type_left;
8453 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8454 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8455 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8456 if (!types_compatible(unqual_left, unqual_right)) {
8458 "subtracting pointers to incompatible types '%T' and '%T'",
8459 orig_type_left, orig_type_right);
8460 } else if (!is_type_object(unqual_left)) {
8461 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8462 errorf(pos, "subtracting pointers to non-object types '%T'",
8464 } else if (warning.other) {
8465 warningf(pos, "subtracting pointers to void");
8468 expression->base.type = type_ptrdiff_t;
8469 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8470 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8471 orig_type_left, orig_type_right);
8475 static void warn_string_literal_address(expression_t const* expr)
8477 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8478 expr = expr->unary.value;
8479 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8481 expr = expr->unary.value;
8484 if (expr->kind == EXPR_STRING_LITERAL ||
8485 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8486 warningf(&expr->base.source_position,
8487 "comparison with string literal results in unspecified behaviour");
8492 * Check the semantics of comparison expressions.
8494 * @param expression The expression to check.
8496 static void semantic_comparison(binary_expression_t *expression)
8498 expression_t *left = expression->left;
8499 expression_t *right = expression->right;
8501 if (warning.address) {
8502 warn_string_literal_address(left);
8503 warn_string_literal_address(right);
8505 expression_t const* const func_left = get_reference_address(left);
8506 if (func_left != NULL && is_null_pointer_constant(right)) {
8507 warningf(&expression->base.source_position,
8508 "the address of '%Y' will never be NULL",
8509 func_left->reference.entity->base.symbol);
8512 expression_t const* const func_right = get_reference_address(right);
8513 if (func_right != NULL && is_null_pointer_constant(right)) {
8514 warningf(&expression->base.source_position,
8515 "the address of '%Y' will never be NULL",
8516 func_right->reference.entity->base.symbol);
8520 type_t *orig_type_left = left->base.type;
8521 type_t *orig_type_right = right->base.type;
8522 type_t *type_left = skip_typeref(orig_type_left);
8523 type_t *type_right = skip_typeref(orig_type_right);
8525 /* TODO non-arithmetic types */
8526 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8527 /* test for signed vs unsigned compares */
8528 if (warning.sign_compare &&
8529 (expression->base.kind != EXPR_BINARY_EQUAL &&
8530 expression->base.kind != EXPR_BINARY_NOTEQUAL) &&
8531 (is_type_signed(type_left) != is_type_signed(type_right))) {
8533 /* check if 1 of the operands is a constant, in this case we just
8534 * check wether we can safely represent the resulting constant in
8535 * the type of the other operand. */
8536 expression_t *const_expr = NULL;
8537 expression_t *other_expr = NULL;
8539 if (is_constant_expression(left)) {
8542 } else if (is_constant_expression(right)) {
8547 if (const_expr != NULL) {
8548 type_t *other_type = skip_typeref(other_expr->base.type);
8549 long val = fold_constant(const_expr);
8550 /* TODO: check if val can be represented by other_type */
8554 warningf(&expression->base.source_position,
8555 "comparison between signed and unsigned");
8557 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8558 expression->left = create_implicit_cast(left, arithmetic_type);
8559 expression->right = create_implicit_cast(right, arithmetic_type);
8560 expression->base.type = arithmetic_type;
8561 if (warning.float_equal &&
8562 (expression->base.kind == EXPR_BINARY_EQUAL ||
8563 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8564 is_type_float(arithmetic_type)) {
8565 warningf(&expression->base.source_position,
8566 "comparing floating point with == or != is unsafe");
8568 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8569 /* TODO check compatibility */
8570 } else if (is_type_pointer(type_left)) {
8571 expression->right = create_implicit_cast(right, type_left);
8572 } else if (is_type_pointer(type_right)) {
8573 expression->left = create_implicit_cast(left, type_right);
8574 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8575 type_error_incompatible("invalid operands in comparison",
8576 &expression->base.source_position,
8577 type_left, type_right);
8579 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8583 * Checks if a compound type has constant fields.
8585 static bool has_const_fields(const compound_type_t *type)
8587 compound_t *compound = type->compound;
8588 entity_t *entry = compound->members.entities;
8590 for (; entry != NULL; entry = entry->base.next) {
8591 if (!is_declaration(entry))
8594 const type_t *decl_type = skip_typeref(entry->declaration.type);
8595 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8602 static bool is_valid_assignment_lhs(expression_t const* const left)
8604 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8605 type_t *const type_left = skip_typeref(orig_type_left);
8607 if (!is_lvalue(left)) {
8608 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8613 if (is_type_array(type_left)) {
8614 errorf(HERE, "cannot assign to arrays ('%E')", left);
8617 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8618 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8622 if (is_type_incomplete(type_left)) {
8623 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8624 left, orig_type_left);
8627 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8628 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8629 left, orig_type_left);
8636 static void semantic_arithmetic_assign(binary_expression_t *expression)
8638 expression_t *left = expression->left;
8639 expression_t *right = expression->right;
8640 type_t *orig_type_left = left->base.type;
8641 type_t *orig_type_right = right->base.type;
8643 if (!is_valid_assignment_lhs(left))
8646 type_t *type_left = skip_typeref(orig_type_left);
8647 type_t *type_right = skip_typeref(orig_type_right);
8649 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8650 /* TODO: improve error message */
8651 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8652 errorf(&expression->base.source_position,
8653 "operation needs arithmetic types");
8658 /* combined instructions are tricky. We can't create an implicit cast on
8659 * the left side, because we need the uncasted form for the store.
8660 * The ast2firm pass has to know that left_type must be right_type
8661 * for the arithmetic operation and create a cast by itself */
8662 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8663 expression->right = create_implicit_cast(right, arithmetic_type);
8664 expression->base.type = type_left;
8667 static void semantic_divmod_assign(binary_expression_t *expression)
8669 semantic_arithmetic_assign(expression);
8670 warn_div_by_zero(expression);
8673 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8675 expression_t *const left = expression->left;
8676 expression_t *const right = expression->right;
8677 type_t *const orig_type_left = left->base.type;
8678 type_t *const orig_type_right = right->base.type;
8679 type_t *const type_left = skip_typeref(orig_type_left);
8680 type_t *const type_right = skip_typeref(orig_type_right);
8682 if (!is_valid_assignment_lhs(left))
8685 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8686 /* combined instructions are tricky. We can't create an implicit cast on
8687 * the left side, because we need the uncasted form for the store.
8688 * The ast2firm pass has to know that left_type must be right_type
8689 * for the arithmetic operation and create a cast by itself */
8690 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8691 expression->right = create_implicit_cast(right, arithmetic_type);
8692 expression->base.type = type_left;
8693 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8694 check_pointer_arithmetic(&expression->base.source_position,
8695 type_left, orig_type_left);
8696 expression->base.type = type_left;
8697 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8698 errorf(&expression->base.source_position,
8699 "incompatible types '%T' and '%T' in assignment",
8700 orig_type_left, orig_type_right);
8705 * Check the semantic restrictions of a logical expression.
8707 static void semantic_logical_op(binary_expression_t *expression)
8709 expression_t *const left = expression->left;
8710 expression_t *const right = expression->right;
8711 type_t *const orig_type_left = left->base.type;
8712 type_t *const orig_type_right = right->base.type;
8713 type_t *const type_left = skip_typeref(orig_type_left);
8714 type_t *const type_right = skip_typeref(orig_type_right);
8716 warn_function_address_as_bool(left);
8717 warn_function_address_as_bool(right);
8719 if (!is_type_scalar(type_left) || !is_type_scalar(type_right)) {
8720 /* TODO: improve error message */
8721 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8722 errorf(&expression->base.source_position,
8723 "operation needs scalar types");
8728 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8732 * Check the semantic restrictions of a binary assign expression.
8734 static void semantic_binexpr_assign(binary_expression_t *expression)
8736 expression_t *left = expression->left;
8737 type_t *orig_type_left = left->base.type;
8739 if (!is_valid_assignment_lhs(left))
8742 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8743 report_assign_error(error, orig_type_left, expression->right,
8744 "assignment", &left->base.source_position);
8745 expression->right = create_implicit_cast(expression->right, orig_type_left);
8746 expression->base.type = orig_type_left;
8750 * Determine if the outermost operation (or parts thereof) of the given
8751 * expression has no effect in order to generate a warning about this fact.
8752 * Therefore in some cases this only examines some of the operands of the
8753 * expression (see comments in the function and examples below).
8755 * f() + 23; // warning, because + has no effect
8756 * x || f(); // no warning, because x controls execution of f()
8757 * x ? y : f(); // warning, because y has no effect
8758 * (void)x; // no warning to be able to suppress the warning
8759 * This function can NOT be used for an "expression has definitely no effect"-
8761 static bool expression_has_effect(const expression_t *const expr)
8763 switch (expr->kind) {
8764 case EXPR_UNKNOWN: break;
8765 case EXPR_INVALID: return true; /* do NOT warn */
8766 case EXPR_REFERENCE: return false;
8767 case EXPR_REFERENCE_ENUM_VALUE: return false;
8768 /* suppress the warning for microsoft __noop operations */
8769 case EXPR_CONST: return expr->conste.is_ms_noop;
8770 case EXPR_CHARACTER_CONSTANT: return false;
8771 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8772 case EXPR_STRING_LITERAL: return false;
8773 case EXPR_WIDE_STRING_LITERAL: return false;
8774 case EXPR_LABEL_ADDRESS: return false;
8777 const call_expression_t *const call = &expr->call;
8778 if (call->function->kind != EXPR_BUILTIN_SYMBOL)
8781 switch (call->function->builtin_symbol.symbol->ID) {
8782 case T___builtin_va_end: return true;
8783 default: return false;
8787 /* Generate the warning if either the left or right hand side of a
8788 * conditional expression has no effect */
8789 case EXPR_CONDITIONAL: {
8790 const conditional_expression_t *const cond = &expr->conditional;
8792 expression_has_effect(cond->true_expression) &&
8793 expression_has_effect(cond->false_expression);
8796 case EXPR_SELECT: return false;
8797 case EXPR_ARRAY_ACCESS: return false;
8798 case EXPR_SIZEOF: return false;
8799 case EXPR_CLASSIFY_TYPE: return false;
8800 case EXPR_ALIGNOF: return false;
8802 case EXPR_FUNCNAME: return false;
8803 case EXPR_BUILTIN_SYMBOL: break; /* handled in EXPR_CALL */
8804 case EXPR_BUILTIN_CONSTANT_P: return false;
8805 case EXPR_BUILTIN_PREFETCH: return true;
8806 case EXPR_OFFSETOF: return false;
8807 case EXPR_VA_START: return true;
8808 case EXPR_VA_ARG: return true;
8809 case EXPR_STATEMENT: return true; // TODO
8810 case EXPR_COMPOUND_LITERAL: return false;
8812 case EXPR_UNARY_NEGATE: return false;
8813 case EXPR_UNARY_PLUS: return false;
8814 case EXPR_UNARY_BITWISE_NEGATE: return false;
8815 case EXPR_UNARY_NOT: return false;
8816 case EXPR_UNARY_DEREFERENCE: return false;
8817 case EXPR_UNARY_TAKE_ADDRESS: return false;
8818 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8819 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8820 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8821 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8823 /* Treat void casts as if they have an effect in order to being able to
8824 * suppress the warning */
8825 case EXPR_UNARY_CAST: {
8826 type_t *const type = skip_typeref(expr->base.type);
8827 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8830 case EXPR_UNARY_CAST_IMPLICIT: return true;
8831 case EXPR_UNARY_ASSUME: return true;
8832 case EXPR_UNARY_DELETE: return true;
8833 case EXPR_UNARY_DELETE_ARRAY: return true;
8834 case EXPR_UNARY_THROW: return true;
8836 case EXPR_BINARY_ADD: return false;
8837 case EXPR_BINARY_SUB: return false;
8838 case EXPR_BINARY_MUL: return false;
8839 case EXPR_BINARY_DIV: return false;
8840 case EXPR_BINARY_MOD: return false;
8841 case EXPR_BINARY_EQUAL: return false;
8842 case EXPR_BINARY_NOTEQUAL: return false;
8843 case EXPR_BINARY_LESS: return false;
8844 case EXPR_BINARY_LESSEQUAL: return false;
8845 case EXPR_BINARY_GREATER: return false;
8846 case EXPR_BINARY_GREATEREQUAL: return false;
8847 case EXPR_BINARY_BITWISE_AND: return false;
8848 case EXPR_BINARY_BITWISE_OR: return false;
8849 case EXPR_BINARY_BITWISE_XOR: return false;
8850 case EXPR_BINARY_SHIFTLEFT: return false;
8851 case EXPR_BINARY_SHIFTRIGHT: return false;
8852 case EXPR_BINARY_ASSIGN: return true;
8853 case EXPR_BINARY_MUL_ASSIGN: return true;
8854 case EXPR_BINARY_DIV_ASSIGN: return true;
8855 case EXPR_BINARY_MOD_ASSIGN: return true;
8856 case EXPR_BINARY_ADD_ASSIGN: return true;
8857 case EXPR_BINARY_SUB_ASSIGN: return true;
8858 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8859 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8860 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8861 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8862 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8864 /* Only examine the right hand side of && and ||, because the left hand
8865 * side already has the effect of controlling the execution of the right
8867 case EXPR_BINARY_LOGICAL_AND:
8868 case EXPR_BINARY_LOGICAL_OR:
8869 /* Only examine the right hand side of a comma expression, because the left
8870 * hand side has a separate warning */
8871 case EXPR_BINARY_COMMA:
8872 return expression_has_effect(expr->binary.right);
8874 case EXPR_BINARY_BUILTIN_EXPECT: return true;
8875 case EXPR_BINARY_ISGREATER: return false;
8876 case EXPR_BINARY_ISGREATEREQUAL: return false;
8877 case EXPR_BINARY_ISLESS: return false;
8878 case EXPR_BINARY_ISLESSEQUAL: return false;
8879 case EXPR_BINARY_ISLESSGREATER: return false;
8880 case EXPR_BINARY_ISUNORDERED: return false;
8883 internal_errorf(HERE, "unexpected expression");
8886 static void semantic_comma(binary_expression_t *expression)
8888 if (warning.unused_value) {
8889 const expression_t *const left = expression->left;
8890 if (!expression_has_effect(left)) {
8891 warningf(&left->base.source_position,
8892 "left-hand operand of comma expression has no effect");
8895 expression->base.type = expression->right->base.type;
8899 * @param prec_r precedence of the right operand
8901 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8902 static expression_t *parse_##binexpression_type(expression_t *left) \
8904 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8905 binexpr->binary.left = left; \
8908 expression_t *right = parse_sub_expression(prec_r); \
8910 binexpr->binary.right = right; \
8911 sfunc(&binexpr->binary); \
8916 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8917 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8918 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8919 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8920 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8921 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8922 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8923 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8924 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8925 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8926 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8927 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8928 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8929 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8930 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8931 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8932 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8933 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8934 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8935 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8936 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8937 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8938 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8939 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8940 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8941 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8942 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8943 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8944 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8945 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8948 static expression_t *parse_sub_expression(precedence_t precedence)
8950 if (token.type < 0) {
8951 return expected_expression_error();
8954 expression_parser_function_t *parser
8955 = &expression_parsers[token.type];
8956 source_position_t source_position = token.source_position;
8959 if (parser->parser != NULL) {
8960 left = parser->parser();
8962 left = parse_primary_expression();
8964 assert(left != NULL);
8965 left->base.source_position = source_position;
8968 if (token.type < 0) {
8969 return expected_expression_error();
8972 parser = &expression_parsers[token.type];
8973 if (parser->infix_parser == NULL)
8975 if (parser->infix_precedence < precedence)
8978 left = parser->infix_parser(left);
8980 assert(left != NULL);
8981 assert(left->kind != EXPR_UNKNOWN);
8982 left->base.source_position = source_position;
8989 * Parse an expression.
8991 static expression_t *parse_expression(void)
8993 return parse_sub_expression(PREC_EXPRESSION);
8997 * Register a parser for a prefix-like operator.
8999 * @param parser the parser function
9000 * @param token_type the token type of the prefix token
9002 static void register_expression_parser(parse_expression_function parser,
9005 expression_parser_function_t *entry = &expression_parsers[token_type];
9007 if (entry->parser != NULL) {
9008 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9009 panic("trying to register multiple expression parsers for a token");
9011 entry->parser = parser;
9015 * Register a parser for an infix operator with given precedence.
9017 * @param parser the parser function
9018 * @param token_type the token type of the infix operator
9019 * @param precedence the precedence of the operator
9021 static void register_infix_parser(parse_expression_infix_function parser,
9022 int token_type, unsigned precedence)
9024 expression_parser_function_t *entry = &expression_parsers[token_type];
9026 if (entry->infix_parser != NULL) {
9027 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9028 panic("trying to register multiple infix expression parsers for a "
9031 entry->infix_parser = parser;
9032 entry->infix_precedence = precedence;
9036 * Initialize the expression parsers.
9038 static void init_expression_parsers(void)
9040 memset(&expression_parsers, 0, sizeof(expression_parsers));
9042 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9043 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9044 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9045 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9046 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9047 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9048 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9049 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9050 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9051 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9052 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9053 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9054 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9055 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9056 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9057 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9058 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9059 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9060 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9061 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9062 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9063 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9064 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9065 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9066 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9067 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9068 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9069 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9070 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9071 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9072 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9073 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9074 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9075 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9076 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9077 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9078 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9080 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9081 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9082 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9083 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9084 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9085 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9086 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9087 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9088 register_expression_parser(parse_sizeof, T_sizeof);
9089 register_expression_parser(parse_alignof, T___alignof__);
9090 register_expression_parser(parse_extension, T___extension__);
9091 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9092 register_expression_parser(parse_delete, T_delete);
9093 register_expression_parser(parse_throw, T_throw);
9097 * Parse a asm statement arguments specification.
9099 static asm_argument_t *parse_asm_arguments(bool is_out)
9101 asm_argument_t *result = NULL;
9102 asm_argument_t *last = NULL;
9104 while (token.type == T_STRING_LITERAL || token.type == '[') {
9105 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9106 memset(argument, 0, sizeof(argument[0]));
9108 if (token.type == '[') {
9110 if (token.type != T_IDENTIFIER) {
9111 parse_error_expected("while parsing asm argument",
9112 T_IDENTIFIER, NULL);
9115 argument->symbol = token.v.symbol;
9120 argument->constraints = parse_string_literals();
9122 add_anchor_token(')');
9123 expression_t *expression = parse_expression();
9124 rem_anchor_token(')');
9126 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9127 * change size or type representation (e.g. int -> long is ok, but
9128 * int -> float is not) */
9129 if (expression->kind == EXPR_UNARY_CAST) {
9130 type_t *const type = expression->base.type;
9131 type_kind_t const kind = type->kind;
9132 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9135 if (kind == TYPE_ATOMIC) {
9136 atomic_type_kind_t const akind = type->atomic.akind;
9137 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9138 size = get_atomic_type_size(akind);
9140 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9141 size = get_atomic_type_size(get_intptr_kind());
9145 expression_t *const value = expression->unary.value;
9146 type_t *const value_type = value->base.type;
9147 type_kind_t const value_kind = value_type->kind;
9149 unsigned value_flags;
9150 unsigned value_size;
9151 if (value_kind == TYPE_ATOMIC) {
9152 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9153 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9154 value_size = get_atomic_type_size(value_akind);
9155 } else if (value_kind == TYPE_POINTER) {
9156 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9157 value_size = get_atomic_type_size(get_intptr_kind());
9162 if (value_flags != flags || value_size != size)
9166 } while (expression->kind == EXPR_UNARY_CAST);
9170 if (!is_lvalue(expression)) {
9171 errorf(&expression->base.source_position,
9172 "asm output argument is not an lvalue");
9175 if (argument->constraints.begin[0] == '+')
9176 mark_vars_read(expression, NULL);
9178 mark_vars_read(expression, NULL);
9180 argument->expression = expression;
9183 set_address_taken(expression, true);
9186 last->next = argument;
9192 if (token.type != ',')
9203 * Parse a asm statement clobber specification.
9205 static asm_clobber_t *parse_asm_clobbers(void)
9207 asm_clobber_t *result = NULL;
9208 asm_clobber_t *last = NULL;
9210 while(token.type == T_STRING_LITERAL) {
9211 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9212 clobber->clobber = parse_string_literals();
9215 last->next = clobber;
9221 if (token.type != ',')
9230 * Parse an asm statement.
9232 static statement_t *parse_asm_statement(void)
9234 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9235 asm_statement_t *asm_statement = &statement->asms;
9239 if (token.type == T_volatile) {
9241 asm_statement->is_volatile = true;
9245 add_anchor_token(')');
9246 add_anchor_token(':');
9247 asm_statement->asm_text = parse_string_literals();
9249 if (token.type != ':') {
9250 rem_anchor_token(':');
9255 asm_statement->outputs = parse_asm_arguments(true);
9256 if (token.type != ':') {
9257 rem_anchor_token(':');
9262 asm_statement->inputs = parse_asm_arguments(false);
9263 if (token.type != ':') {
9264 rem_anchor_token(':');
9267 rem_anchor_token(':');
9270 asm_statement->clobbers = parse_asm_clobbers();
9273 rem_anchor_token(')');
9277 if (asm_statement->outputs == NULL) {
9278 /* GCC: An 'asm' instruction without any output operands will be treated
9279 * identically to a volatile 'asm' instruction. */
9280 asm_statement->is_volatile = true;
9285 return create_invalid_statement();
9289 * Parse a case statement.
9291 static statement_t *parse_case_statement(void)
9293 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9294 source_position_t *const pos = &statement->base.source_position;
9298 expression_t *const expression = parse_expression();
9299 statement->case_label.expression = expression;
9300 if (!is_constant_expression(expression)) {
9301 /* This check does not prevent the error message in all cases of an
9302 * prior error while parsing the expression. At least it catches the
9303 * common case of a mistyped enum entry. */
9304 if (is_type_valid(skip_typeref(expression->base.type))) {
9305 errorf(pos, "case label does not reduce to an integer constant");
9307 statement->case_label.is_bad = true;
9309 long const val = fold_constant(expression);
9310 statement->case_label.first_case = val;
9311 statement->case_label.last_case = val;
9315 if (token.type == T_DOTDOTDOT) {
9317 expression_t *const end_range = parse_expression();
9318 statement->case_label.end_range = end_range;
9319 if (!is_constant_expression(end_range)) {
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(end_range->base.type))) {
9324 errorf(pos, "case range does not reduce to an integer constant");
9326 statement->case_label.is_bad = true;
9328 long const val = fold_constant(end_range);
9329 statement->case_label.last_case = val;
9331 if (warning.other && val < statement->case_label.first_case) {
9332 statement->case_label.is_empty_range = true;
9333 warningf(pos, "empty range specified");
9339 PUSH_PARENT(statement);
9343 if (current_switch != NULL) {
9344 if (! statement->case_label.is_bad) {
9345 /* Check for duplicate case values */
9346 case_label_statement_t *c = &statement->case_label;
9347 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9348 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9351 if (c->last_case < l->first_case || c->first_case > l->last_case)
9354 errorf(pos, "duplicate case value (previously used %P)",
9355 &l->base.source_position);
9359 /* link all cases into the switch statement */
9360 if (current_switch->last_case == NULL) {
9361 current_switch->first_case = &statement->case_label;
9363 current_switch->last_case->next = &statement->case_label;
9365 current_switch->last_case = &statement->case_label;
9367 errorf(pos, "case label not within a switch statement");
9370 statement_t *const inner_stmt = parse_statement();
9371 statement->case_label.statement = inner_stmt;
9372 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9373 errorf(&inner_stmt->base.source_position, "declaration after case label");
9380 return create_invalid_statement();
9384 * Parse a default statement.
9386 static statement_t *parse_default_statement(void)
9388 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9392 PUSH_PARENT(statement);
9395 if (current_switch != NULL) {
9396 const case_label_statement_t *def_label = current_switch->default_label;
9397 if (def_label != NULL) {
9398 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9399 &def_label->base.source_position);
9401 current_switch->default_label = &statement->case_label;
9403 /* link all cases into the switch statement */
9404 if (current_switch->last_case == NULL) {
9405 current_switch->first_case = &statement->case_label;
9407 current_switch->last_case->next = &statement->case_label;
9409 current_switch->last_case = &statement->case_label;
9412 errorf(&statement->base.source_position,
9413 "'default' label not within a switch statement");
9416 statement_t *const inner_stmt = parse_statement();
9417 statement->case_label.statement = inner_stmt;
9418 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9419 errorf(&inner_stmt->base.source_position, "declaration after default label");
9426 return create_invalid_statement();
9430 * Parse a label statement.
9432 static statement_t *parse_label_statement(void)
9434 assert(token.type == T_IDENTIFIER);
9435 symbol_t *symbol = token.v.symbol;
9436 label_t *label = get_label(symbol);
9438 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9439 statement->label.label = label;
9443 PUSH_PARENT(statement);
9445 /* if statement is already set then the label is defined twice,
9446 * otherwise it was just mentioned in a goto/local label declaration so far
9448 if (label->statement != NULL) {
9449 errorf(HERE, "duplicate label '%Y' (declared %P)",
9450 symbol, &label->base.source_position);
9452 label->base.source_position = token.source_position;
9453 label->statement = statement;
9458 if (token.type == '}') {
9459 /* TODO only warn? */
9460 if (warning.other && false) {
9461 warningf(HERE, "label at end of compound statement");
9462 statement->label.statement = create_empty_statement();
9464 errorf(HERE, "label at end of compound statement");
9465 statement->label.statement = create_invalid_statement();
9467 } else if (token.type == ';') {
9468 /* Eat an empty statement here, to avoid the warning about an empty
9469 * statement after a label. label:; is commonly used to have a label
9470 * before a closing brace. */
9471 statement->label.statement = create_empty_statement();
9474 statement_t *const inner_stmt = parse_statement();
9475 statement->label.statement = inner_stmt;
9476 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9477 errorf(&inner_stmt->base.source_position, "declaration after label");
9481 /* remember the labels in a list for later checking */
9482 if (label_last == NULL) {
9483 label_first = &statement->label;
9485 label_last->next = &statement->label;
9487 label_last = &statement->label;
9494 * Parse an if statement.
9496 static statement_t *parse_if(void)
9498 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9502 PUSH_PARENT(statement);
9504 add_anchor_token('{');
9507 add_anchor_token(')');
9508 expression_t *const expr = parse_expression();
9509 statement->ifs.condition = expr;
9510 mark_vars_read(expr, NULL);
9511 rem_anchor_token(')');
9515 rem_anchor_token('{');
9517 add_anchor_token(T_else);
9518 statement->ifs.true_statement = parse_statement();
9519 rem_anchor_token(T_else);
9521 if (token.type == T_else) {
9523 statement->ifs.false_statement = parse_statement();
9531 * Check that all enums are handled in a switch.
9533 * @param statement the switch statement to check
9535 static void check_enum_cases(const switch_statement_t *statement) {
9536 const type_t *type = skip_typeref(statement->expression->base.type);
9537 if (! is_type_enum(type))
9539 const enum_type_t *enumt = &type->enumt;
9541 /* if we have a default, no warnings */
9542 if (statement->default_label != NULL)
9545 /* FIXME: calculation of value should be done while parsing */
9546 /* TODO: quadratic algorithm here. Change to an n log n one */
9547 long last_value = -1;
9548 const entity_t *entry = enumt->enume->base.next;
9549 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9550 entry = entry->base.next) {
9551 const expression_t *expression = entry->enum_value.value;
9552 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9554 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9555 if (l->expression == NULL)
9557 if (l->first_case <= value && value <= l->last_case) {
9563 warningf(&statement->base.source_position,
9564 "enumeration value '%Y' not handled in switch",
9565 entry->base.symbol);
9572 * Parse a switch statement.
9574 static statement_t *parse_switch(void)
9576 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9580 PUSH_PARENT(statement);
9583 add_anchor_token(')');
9584 expression_t *const expr = parse_expression();
9585 mark_vars_read(expr, NULL);
9586 type_t * type = skip_typeref(expr->base.type);
9587 if (is_type_integer(type)) {
9588 type = promote_integer(type);
9589 if (warning.traditional) {
9590 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9591 warningf(&expr->base.source_position,
9592 "'%T' switch expression not converted to '%T' in ISO C",
9596 } else if (is_type_valid(type)) {
9597 errorf(&expr->base.source_position,
9598 "switch quantity is not an integer, but '%T'", type);
9599 type = type_error_type;
9601 statement->switchs.expression = create_implicit_cast(expr, type);
9603 rem_anchor_token(')');
9605 switch_statement_t *rem = current_switch;
9606 current_switch = &statement->switchs;
9607 statement->switchs.body = parse_statement();
9608 current_switch = rem;
9610 if (warning.switch_default &&
9611 statement->switchs.default_label == NULL) {
9612 warningf(&statement->base.source_position, "switch has no default case");
9614 if (warning.switch_enum)
9615 check_enum_cases(&statement->switchs);
9621 return create_invalid_statement();
9624 static statement_t *parse_loop_body(statement_t *const loop)
9626 statement_t *const rem = current_loop;
9627 current_loop = loop;
9629 statement_t *const body = parse_statement();
9636 * Parse a while statement.
9638 static statement_t *parse_while(void)
9640 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9644 PUSH_PARENT(statement);
9647 add_anchor_token(')');
9648 expression_t *const cond = parse_expression();
9649 statement->whiles.condition = cond;
9650 mark_vars_read(cond, NULL);
9651 rem_anchor_token(')');
9654 statement->whiles.body = parse_loop_body(statement);
9660 return create_invalid_statement();
9664 * Parse a do statement.
9666 static statement_t *parse_do(void)
9668 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9672 PUSH_PARENT(statement);
9674 add_anchor_token(T_while);
9675 statement->do_while.body = parse_loop_body(statement);
9676 rem_anchor_token(T_while);
9680 add_anchor_token(')');
9681 expression_t *const cond = parse_expression();
9682 statement->do_while.condition = cond;
9683 mark_vars_read(cond, NULL);
9684 rem_anchor_token(')');
9692 return create_invalid_statement();
9696 * Parse a for statement.
9698 static statement_t *parse_for(void)
9700 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9704 PUSH_PARENT(statement);
9706 size_t const top = environment_top();
9707 scope_push(&statement->fors.scope);
9710 add_anchor_token(')');
9712 if (token.type != ';') {
9713 if (is_declaration_specifier(&token, false)) {
9714 parse_declaration(record_entity);
9716 add_anchor_token(';');
9717 expression_t *const init = parse_expression();
9718 statement->fors.initialisation = init;
9719 mark_vars_read(init, VAR_ANY);
9720 if (warning.unused_value && !expression_has_effect(init)) {
9721 warningf(&init->base.source_position,
9722 "initialisation of 'for'-statement has no effect");
9724 rem_anchor_token(';');
9731 if (token.type != ';') {
9732 add_anchor_token(';');
9733 expression_t *const cond = parse_expression();
9734 statement->fors.condition = cond;
9735 mark_vars_read(cond, NULL);
9736 rem_anchor_token(';');
9739 if (token.type != ')') {
9740 expression_t *const step = parse_expression();
9741 statement->fors.step = step;
9742 mark_vars_read(step, VAR_ANY);
9743 if (warning.unused_value && !expression_has_effect(step)) {
9744 warningf(&step->base.source_position,
9745 "step of 'for'-statement has no effect");
9749 rem_anchor_token(')');
9750 statement->fors.body = parse_loop_body(statement);
9752 assert(scope == &statement->fors.scope);
9754 environment_pop_to(top);
9761 rem_anchor_token(')');
9762 assert(scope == &statement->fors.scope);
9764 environment_pop_to(top);
9766 return create_invalid_statement();
9770 * Parse a goto statement.
9772 static statement_t *parse_goto(void)
9774 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9777 if (GNU_MODE && token.type == '*') {
9779 expression_t *expression = parse_expression();
9780 mark_vars_read(expression, NULL);
9782 /* Argh: although documentation say the expression must be of type void *,
9783 * gcc excepts anything that can be casted into void * without error */
9784 type_t *type = expression->base.type;
9786 if (type != type_error_type) {
9787 if (!is_type_pointer(type) && !is_type_integer(type)) {
9788 errorf(&expression->base.source_position,
9789 "cannot convert to a pointer type");
9790 } else if (warning.other && type != type_void_ptr) {
9791 warningf(&expression->base.source_position,
9792 "type of computed goto expression should be 'void*' not '%T'", type);
9794 expression = create_implicit_cast(expression, type_void_ptr);
9797 statement->gotos.expression = expression;
9799 if (token.type != T_IDENTIFIER) {
9801 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9803 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9807 symbol_t *symbol = token.v.symbol;
9810 statement->gotos.label = get_label(symbol);
9813 /* remember the goto's in a list for later checking */
9814 if (goto_last == NULL) {
9815 goto_first = &statement->gotos;
9817 goto_last->next = &statement->gotos;
9819 goto_last = &statement->gotos;
9825 return create_invalid_statement();
9829 * Parse a continue statement.
9831 static statement_t *parse_continue(void)
9833 if (current_loop == NULL) {
9834 errorf(HERE, "continue statement not within loop");
9837 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9847 * Parse a break statement.
9849 static statement_t *parse_break(void)
9851 if (current_switch == NULL && current_loop == NULL) {
9852 errorf(HERE, "break statement not within loop or switch");
9855 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9865 * Parse a __leave statement.
9867 static statement_t *parse_leave_statement(void)
9869 if (current_try == NULL) {
9870 errorf(HERE, "__leave statement not within __try");
9873 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9883 * Check if a given entity represents a local variable.
9885 static bool is_local_variable(const entity_t *entity)
9887 if (entity->kind != ENTITY_VARIABLE)
9890 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9891 case STORAGE_CLASS_AUTO:
9892 case STORAGE_CLASS_REGISTER: {
9893 const type_t *type = skip_typeref(entity->declaration.type);
9894 if (is_type_function(type)) {
9906 * Check if a given expression represents a local variable.
9908 static bool expression_is_local_variable(const expression_t *expression)
9910 if (expression->base.kind != EXPR_REFERENCE) {
9913 const entity_t *entity = expression->reference.entity;
9914 return is_local_variable(entity);
9918 * Check if a given expression represents a local variable and
9919 * return its declaration then, else return NULL.
9921 entity_t *expression_is_variable(const expression_t *expression)
9923 if (expression->base.kind != EXPR_REFERENCE) {
9926 entity_t *entity = expression->reference.entity;
9927 if (entity->kind != ENTITY_VARIABLE)
9934 * Parse a return statement.
9936 static statement_t *parse_return(void)
9940 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9942 expression_t *return_value = NULL;
9943 if (token.type != ';') {
9944 return_value = parse_expression();
9945 mark_vars_read(return_value, NULL);
9948 const type_t *const func_type = current_function->base.type;
9949 assert(is_type_function(func_type));
9950 type_t *const return_type = skip_typeref(func_type->function.return_type);
9952 if (return_value != NULL) {
9953 type_t *return_value_type = skip_typeref(return_value->base.type);
9955 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID) &&
9956 !is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9957 if (warning.other) {
9958 warningf(&statement->base.source_position,
9959 "'return' with a value, in function returning void");
9961 return_value = NULL;
9963 assign_error_t error = semantic_assign(return_type, return_value);
9964 report_assign_error(error, return_type, return_value, "'return'",
9965 &statement->base.source_position);
9966 return_value = create_implicit_cast(return_value, return_type);
9968 /* check for returning address of a local var */
9969 if (warning.other && return_value != NULL
9970 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9971 const expression_t *expression = return_value->unary.value;
9972 if (expression_is_local_variable(expression)) {
9973 warningf(&statement->base.source_position,
9974 "function returns address of local variable");
9977 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9978 warningf(&statement->base.source_position,
9979 "'return' without value, in function returning non-void");
9981 statement->returns.value = return_value;
9990 * Parse a declaration statement.
9992 static statement_t *parse_declaration_statement(void)
9994 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9996 entity_t *before = scope->last_entity;
9998 parse_external_declaration();
10000 parse_declaration(record_entity);
10002 if (before == NULL) {
10003 statement->declaration.declarations_begin = scope->entities;
10005 statement->declaration.declarations_begin = before->base.next;
10007 statement->declaration.declarations_end = scope->last_entity;
10013 * Parse an expression statement, ie. expr ';'.
10015 static statement_t *parse_expression_statement(void)
10017 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10019 expression_t *const expr = parse_expression();
10020 statement->expression.expression = expr;
10021 mark_vars_read(expr, VAR_ANY);
10030 * Parse a microsoft __try { } __finally { } or
10031 * __try{ } __except() { }
10033 static statement_t *parse_ms_try_statment(void)
10035 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10038 PUSH_PARENT(statement);
10040 ms_try_statement_t *rem = current_try;
10041 current_try = &statement->ms_try;
10042 statement->ms_try.try_statement = parse_compound_statement(false);
10047 if (token.type == T___except) {
10050 add_anchor_token(')');
10051 expression_t *const expr = parse_expression();
10052 mark_vars_read(expr, NULL);
10053 type_t * type = skip_typeref(expr->base.type);
10054 if (is_type_integer(type)) {
10055 type = promote_integer(type);
10056 } else if (is_type_valid(type)) {
10057 errorf(&expr->base.source_position,
10058 "__expect expression is not an integer, but '%T'", type);
10059 type = type_error_type;
10061 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10062 rem_anchor_token(')');
10064 statement->ms_try.final_statement = parse_compound_statement(false);
10065 } else if (token.type == T__finally) {
10067 statement->ms_try.final_statement = parse_compound_statement(false);
10069 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10070 return create_invalid_statement();
10074 return create_invalid_statement();
10077 static statement_t *parse_empty_statement(void)
10079 if (warning.empty_statement) {
10080 warningf(HERE, "statement is empty");
10082 statement_t *const statement = create_empty_statement();
10087 static statement_t *parse_local_label_declaration(void)
10089 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10093 entity_t *begin = NULL, *end = NULL;
10096 if (token.type != T_IDENTIFIER) {
10097 parse_error_expected("while parsing local label declaration",
10098 T_IDENTIFIER, NULL);
10101 symbol_t *symbol = token.v.symbol;
10102 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10103 if (entity != NULL && entity->base.parent_scope == scope) {
10104 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10105 symbol, &entity->base.source_position);
10107 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10109 entity->base.parent_scope = scope;
10110 entity->base.namespc = NAMESPACE_LABEL;
10111 entity->base.source_position = token.source_position;
10112 entity->base.symbol = symbol;
10115 end->base.next = entity;
10120 environment_push(entity);
10124 if (token.type != ',')
10130 statement->declaration.declarations_begin = begin;
10131 statement->declaration.declarations_end = end;
10136 * Parse a statement.
10137 * There's also parse_statement() which additionally checks for
10138 * "statement has no effect" warnings
10140 static statement_t *intern_parse_statement(void)
10142 statement_t *statement = NULL;
10144 /* declaration or statement */
10145 add_anchor_token(';');
10146 switch (token.type) {
10147 case T_IDENTIFIER: {
10148 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10149 if (la1_type == ':') {
10150 statement = parse_label_statement();
10151 } else if (is_typedef_symbol(token.v.symbol)) {
10152 statement = parse_declaration_statement();
10154 /* it's an identifier, the grammar says this must be an
10155 * expression statement. However it is common that users mistype
10156 * declaration types, so we guess a bit here to improve robustness
10157 * for incorrect programs */
10158 switch (la1_type) {
10160 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10161 goto expression_statment;
10166 statement = parse_declaration_statement();
10170 expression_statment:
10171 statement = parse_expression_statement();
10178 case T___extension__:
10179 /* This can be a prefix to a declaration or an expression statement.
10180 * We simply eat it now and parse the rest with tail recursion. */
10183 } while (token.type == T___extension__);
10184 bool old_gcc_extension = in_gcc_extension;
10185 in_gcc_extension = true;
10186 statement = parse_statement();
10187 in_gcc_extension = old_gcc_extension;
10191 statement = parse_declaration_statement();
10195 statement = parse_local_label_declaration();
10198 case ';': statement = parse_empty_statement(); break;
10199 case '{': statement = parse_compound_statement(false); break;
10200 case T___leave: statement = parse_leave_statement(); break;
10201 case T___try: statement = parse_ms_try_statment(); break;
10202 case T_asm: statement = parse_asm_statement(); break;
10203 case T_break: statement = parse_break(); break;
10204 case T_case: statement = parse_case_statement(); break;
10205 case T_continue: statement = parse_continue(); break;
10206 case T_default: statement = parse_default_statement(); break;
10207 case T_do: statement = parse_do(); break;
10208 case T_for: statement = parse_for(); break;
10209 case T_goto: statement = parse_goto(); break;
10210 case T_if: statement = parse_if(); break;
10211 case T_return: statement = parse_return(); break;
10212 case T_switch: statement = parse_switch(); break;
10213 case T_while: statement = parse_while(); break;
10216 statement = parse_expression_statement();
10220 errorf(HERE, "unexpected token %K while parsing statement", &token);
10221 statement = create_invalid_statement();
10226 rem_anchor_token(';');
10228 assert(statement != NULL
10229 && statement->base.source_position.input_name != NULL);
10235 * parse a statement and emits "statement has no effect" warning if needed
10236 * (This is really a wrapper around intern_parse_statement with check for 1
10237 * single warning. It is needed, because for statement expressions we have
10238 * to avoid the warning on the last statement)
10240 static statement_t *parse_statement(void)
10242 statement_t *statement = intern_parse_statement();
10244 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10245 expression_t *expression = statement->expression.expression;
10246 if (!expression_has_effect(expression)) {
10247 warningf(&expression->base.source_position,
10248 "statement has no effect");
10256 * Parse a compound statement.
10258 static statement_t *parse_compound_statement(bool inside_expression_statement)
10260 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10262 PUSH_PARENT(statement);
10265 add_anchor_token('}');
10267 size_t const top = environment_top();
10268 scope_push(&statement->compound.scope);
10270 statement_t **anchor = &statement->compound.statements;
10271 bool only_decls_so_far = true;
10272 while (token.type != '}') {
10273 if (token.type == T_EOF) {
10274 errorf(&statement->base.source_position,
10275 "EOF while parsing compound statement");
10278 statement_t *sub_statement = intern_parse_statement();
10279 if (is_invalid_statement(sub_statement)) {
10280 /* an error occurred. if we are at an anchor, return */
10286 if (warning.declaration_after_statement) {
10287 if (sub_statement->kind != STATEMENT_DECLARATION) {
10288 only_decls_so_far = false;
10289 } else if (!only_decls_so_far) {
10290 warningf(&sub_statement->base.source_position,
10291 "ISO C90 forbids mixed declarations and code");
10295 *anchor = sub_statement;
10297 while (sub_statement->base.next != NULL)
10298 sub_statement = sub_statement->base.next;
10300 anchor = &sub_statement->base.next;
10304 /* look over all statements again to produce no effect warnings */
10305 if (warning.unused_value) {
10306 statement_t *sub_statement = statement->compound.statements;
10307 for( ; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10308 if (sub_statement->kind != STATEMENT_EXPRESSION)
10310 /* don't emit a warning for the last expression in an expression
10311 * statement as it has always an effect */
10312 if (inside_expression_statement && sub_statement->base.next == NULL)
10315 expression_t *expression = sub_statement->expression.expression;
10316 if (!expression_has_effect(expression)) {
10317 warningf(&expression->base.source_position,
10318 "statement has no effect");
10324 rem_anchor_token('}');
10325 assert(scope == &statement->compound.scope);
10327 environment_pop_to(top);
10334 * Check for unused global static functions and variables
10336 static void check_unused_globals(void)
10338 if (!warning.unused_function && !warning.unused_variable)
10341 for (const entity_t *entity = file_scope->entities; entity != NULL;
10342 entity = entity->base.next) {
10343 if (!is_declaration(entity))
10346 const declaration_t *declaration = &entity->declaration;
10347 if (declaration->used ||
10348 declaration->modifiers & DM_UNUSED ||
10349 declaration->modifiers & DM_USED ||
10350 declaration->storage_class != STORAGE_CLASS_STATIC)
10353 type_t *const type = declaration->type;
10355 if (entity->kind == ENTITY_FUNCTION) {
10356 /* inhibit warning for static inline functions */
10357 if (entity->function.is_inline)
10360 s = entity->function.statement != NULL ? "defined" : "declared";
10365 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10366 type, declaration->base.symbol, s);
10370 static void parse_global_asm(void)
10372 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10377 statement->asms.asm_text = parse_string_literals();
10378 statement->base.next = unit->global_asm;
10379 unit->global_asm = statement;
10388 * Parse a translation unit.
10390 static void parse_translation_unit(void)
10392 add_anchor_token(T_EOF);
10395 unsigned char token_anchor_copy[T_LAST_TOKEN];
10396 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10400 bool anchor_leak = false;
10401 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10402 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10404 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10405 anchor_leak = true;
10408 if (in_gcc_extension) {
10409 errorf(HERE, "Leaked __extension__");
10410 anchor_leak = true;
10417 switch (token.type) {
10420 case T___extension__:
10421 parse_external_declaration();
10425 parse_global_asm();
10429 rem_anchor_token(T_EOF);
10433 if (!strict_mode) {
10435 warningf(HERE, "stray ';' outside of function");
10442 errorf(HERE, "stray %K outside of function", &token);
10443 if (token.type == '(' || token.type == '{' || token.type == '[')
10444 eat_until_matching_token(token.type);
10454 * @return the translation unit or NULL if errors occurred.
10456 void start_parsing(void)
10458 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10459 label_stack = NEW_ARR_F(stack_entry_t, 0);
10460 diagnostic_count = 0;
10464 type_set_output(stderr);
10465 ast_set_output(stderr);
10467 assert(unit == NULL);
10468 unit = allocate_ast_zero(sizeof(unit[0]));
10470 assert(file_scope == NULL);
10471 file_scope = &unit->scope;
10473 assert(scope == NULL);
10474 scope_push(&unit->scope);
10477 translation_unit_t *finish_parsing(void)
10479 /* do NOT use scope_pop() here, this will crash, will it by hand */
10480 assert(scope == &unit->scope);
10483 assert(file_scope == &unit->scope);
10484 check_unused_globals();
10487 DEL_ARR_F(environment_stack);
10488 DEL_ARR_F(label_stack);
10490 translation_unit_t *result = unit;
10497 lookahead_bufpos = 0;
10498 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10501 parse_translation_unit();
10505 * Initialize the parser.
10507 void init_parser(void)
10509 sym_anonymous = symbol_table_insert("<anonymous>");
10511 if (c_mode & _MS) {
10512 /* add predefined symbols for extended-decl-modifier */
10513 sym_align = symbol_table_insert("align");
10514 sym_allocate = symbol_table_insert("allocate");
10515 sym_dllimport = symbol_table_insert("dllimport");
10516 sym_dllexport = symbol_table_insert("dllexport");
10517 sym_naked = symbol_table_insert("naked");
10518 sym_noinline = symbol_table_insert("noinline");
10519 sym_noreturn = symbol_table_insert("noreturn");
10520 sym_nothrow = symbol_table_insert("nothrow");
10521 sym_novtable = symbol_table_insert("novtable");
10522 sym_property = symbol_table_insert("property");
10523 sym_get = symbol_table_insert("get");
10524 sym_put = symbol_table_insert("put");
10525 sym_selectany = symbol_table_insert("selectany");
10526 sym_thread = symbol_table_insert("thread");
10527 sym_uuid = symbol_table_insert("uuid");
10528 sym_deprecated = symbol_table_insert("deprecated");
10529 sym_restrict = symbol_table_insert("restrict");
10530 sym_noalias = symbol_table_insert("noalias");
10532 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10534 init_expression_parsers();
10535 obstack_init(&temp_obst);
10537 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10538 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10542 * Terminate the parser.
10544 void exit_parser(void)
10546 obstack_free(&temp_obst, NULL);